Skip to content
Tech Interview Prep
Technical interview guide

Distributed Data Processing

How frameworks like Spark parallelize work across a cluster: partitioning, shuffling, and their costs.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Apache Spark 4.2 documentation, Apache Beam and Apache Hadoop current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain how a distributed Spark job is executed.

Answer

Assumptions: Spark 3.5, sort-based shuffle, Adaptive Query Execution on (default since 3.2), YARN or Kubernetes, input on HDFS/S3. Numbers below are the defaults unless stated.

The 90-second answer

A Spark job is one driver process plus a pool of executors. Transformations (map, filter, join) only build a lazy logical plan: nothing runs. An action (count, collect, save) hands that plan to Catalyst, which produces a physical plan; DAGScheduler then cuts the plan into stages at every wide dependency, i.e. every shuffle. Inside a stage, narrow operators pipeline in a single pass over each partition, so no intermediate result is materialized.

Each stage becomes one task per partition, launched by TaskScheduler onto executor slots. A task reads its input split (an HDFS block, or shuffle blocks from the previous stage), computes, spills to local disk when it outgrows its memory share, and writes shuffle files or final output. The driver holds the DAG, stage/task state and shuffle metadata, never the data, which is why collect() on a large result OOMs the driver rather than the executors.

Trace: what actually gets scheduled

Python
rdd = sc.textFile("hdfs:///logs/*.gz", 2000)      # 2000 partitions
counts = (rdd
    .flatMap(lambda l: l.split())
    .map(lambda w: (w, 1))
    .reduceByKey(lambda a, b: a + b, 200)          # wide dependency
    .filter(lambda kv: kv[1] > 100)
    .count())                                      # action
StageTasksWork per taskBoundary
02000read one HDFS block, flatMap, map, write 200 shuffle bucketsshuffle write
1200fetch its bucket from all 2000 map outputs, reduceByKey, filter, emit partial countshuffle read
——driver sums 200 partial countsaction result

flatMap and map never get their own stage: they pipeline inside stage 0. reduceByKey is the only shuffle boundary, so it is the only stage cut. Shuffle block count is 2000 × 200 = 400,000 files, which is why shuffle-heavy jobs are I/O-bound on small files, not CPU-bound.

Trade-offs that decide the plan

  • repartition(n) vs coalesce(n). repartition does a full shuffle to redistribute evenly; coalesce merges adjacent partitions with no shuffle. Use coalesce to shrink before a write, repartition when you need even key distribution or more parallelism.
  • Broadcast vs sort-merge join. spark.sql.autoBroadcastJoinThreshold defaults to 10 MB; below it the build side is shipped to every executor and the join needs no shuffle. Above it, sort-merge shuffles both sides: more network, but it scales.
  • spark.sql.shuffle.partitions defaults to 200. Correct for small data, wrong for a 1 TB shuffle: 200 partitions means ~5 GB per reduce task. AQE coalesces partitions down toward spark.sql.adaptive.advisoryPartitionSizeInBytes (64 MB) at runtime, so the static 200 is a starting point, not the final count.

Failure modes and how you see them

  • Skew. One reduce partition holds most keys; that task runs 10× longer while the rest idle. Visible in the Spark UI stage page as max task duration far above the median. AQE skew-join handling (spark.sql.adaptive.skewJoin.enabled, default true) splits oversized partitions; salting the key is the manual fallback.
  • Executor OOM. A task's working set exceeds its memory share (spark.memory.fraction defaults to 0.6 of heap). Spill metrics in the UI climb before the kill: spilling is the warning, not the failure.
  • Shuffle fetch failure. An executor dies and its map outputs are gone, so downstream tasks report FetchFailed and Spark re-runs the map stage. spark.stage.maxConsecutiveAttempts (default 4) bounds the retries before the job fails.
  • Task retries. spark.task.maxFailures defaults to 4 attempts per task; lineage recomputes only the lost partition.

What would change this answer: a pure DataFrame/SQL job lets AQE rewrite the physical plan mid-execution, and a Structured Streaming job repeats the whole stage graph once per micro-batch.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Explain narrow and wide dependencies and why they matter.

Answer

The 90-second answer. A dependency is narrow when each child partition is computed from one parent partition (or a bounded, known set of them), and wide when each child partition needs rows from many parent partitions. Narrow lets the scheduler pipeline operators inside a single stage: no materialization, no network. Wide forces a shuffle: every parent partition writes its output to disk keyed by target partition, and the next stage fetches it. That stage boundary is why wide dependencies cost so much and why recovery differs: a lost narrow partition is recomputed from its parent, while a lost shuffle map output forces the upstream stage to re-run. Assume Spark 3.5 with AQE on (default since 3.2).

NarrowWide
Examplesmap, filter, union, coalesce, broadcast joingroupBy, distinct, repartition, global sort, sort-merge join
Stage shapepipelined in one stagestage boundary + shuffle
Movementnone, or localnetwork + disk
Recoveryrecompute from parent partitionrecompute map stage if shuffle files are lost
Partitioningpreservedreplaced by key/range
Python
# PySpark 3.5
df = spark.read.parquet("s3://events/")          # 1 TB, ~8000 files
out = (df.filter("country = 'US'")               # narrow, pushed into the scan
         .groupBy("user_id")                     # wide: shuffle by user_id
         .agg(F.sum("bytes").alias("total")))
out.write.parquet("s3://out/")

Trace: Stage 0 scans and filters, then does a map-side partial sum per input partition and writes shuffle files. Stage 1 fetches each user_id's partial sums, finishes the sum, writes Parquet. The filter never crosses the network; the groupBy does.

Arithmetic: 1 TB of shuffle write across the default spark.sql.shuffle.partitions=200 is ~5.1 GB per reduce partition. Each reduce task fetches at most spark.reducer.maxSizeInFlight=48 MB per request, so ~107 fetch round trips before it can aggregate, and 5.1 GB will spill. Raising spark.sql.shuffle.partitions to 4000 gives ~256 MB per partition; AQE coalescing (advisoryPartitionSizeInBytes=64 MB) then merges any that come out small. AQE coalescing only merges, it cannot split a 5.1 GB partition, so the partition count is the knob that fixes spill.

Failure modes and how you see them.

  • Skewed partition: one user_id holds 40% of rows, so one reduce task runs 10x longer than its peers. Detect in the Spark UI stage view by comparing max task duration against p75, or shuffle-read bytes per task. AQE skew join (skewedPartitionFactor=5, skewedPartitionThresholdInBytes=256 MB) splits it, but only for joins.
  • Shuffle fetch failure: FetchFailedException when a map output is gone. Executor killed, disk full, node lost. Detect from Failed to connect to ... shuffle in the logs; spark.shuffle.io.maxRetries=3 with retryWait=5s runs before the stage is retried.
  • Disk spill: the reduce-side aggregation buffer overflows. Detect via the Spark UI "Shuffle Spill (Memory)" and "(Disk)" columns; a task spilling gigabytes is a partition-size problem, not a memory problem.
  • Reduce-side OOM: a single partition larger than the executor heap. Same signal as spill, one step further.

When a wide dependency is worth it. You pay the shuffle when you need a global result: a correct groupBy, a sort-merge join of two large tables, a global sort. You avoid it when you can get the same answer without one: pre-aggregate before the exchange (map-side combine already does this for agg), broadcast a small side to turn a join narrow (spark.sql.autoBroadcastJoinThreshold=10 MB default), or co-partition two tables once and reuse that partitioning across repeated joins. Narrow-only pipelines are cheaper but cannot produce a global aggregate; if the question needs one, the shuffle is the answer, and the job is to size it, not to dodge it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Compare repartition and coalesce decisions.

Answer

Answer

Repartition is a wide transformation: it inserts an Exchange and rewrites the data into the requested number of partitions. Coalesce is narrow: it merges existing partitions without moving data across the network. That one difference decides almost every case.

Assumptions: Spark 3.x, AQE on (default since 3.2.0).

repartition(n) uses RoundRobinPartitioning; repartition(n, col) uses HashPartitioning on col. Both produce exactly n partitions and a full shuffle write plus read. coalesce(n) only ever reduces: asking for more partitions than exist leaves the count unchanged, a silent no-op that catches anyone reaching for coalesce to raise parallelism. coalesce(n) groups the existing partitions into n tasks; each task reads its parents sequentially in memory.

repartition(n)repartition(n, col)coalesce(n)
planExchange RoundRobinPartitioning(n)Exchange hashpartitioning(col, n)Coalesce n (no Exchange)
shufflefull write+readfull write+readnone
countup or downup or downdown only
balanceeven by sizeeven by key, skew possibleinherits upstream imbalance
output filesnnn, uneven sizes

Worked example (illustrative): a 30 GB DataFrame after a groupBy, 200 shuffle partitions → ~150 MB each. coalesce(20): 20 tasks, each reading 10 parents. If one key holds 2 GB, its parent partition is 2 GB and the task that owns it runs ~13x longer than its peers: the job's wall clock is set by that straggler. repartition(20): 20 tasks of ~1.5 GB each, even, but you pay a 30 GB shuffle write and read to get there. If the shuffle is already there and AQE is on, Spark coalesces to advisoryPartitionSizeInBytes = 64 MB on its own; a manual coalesce(20) after that just undoes the sizing.

When to use which:

  • repartition(n, col) before a keyed join or aggregate when the current partitioning doesn't match the key: it removes a later shuffle, or makes the join map-side when the other side is already partitioned on the same key.
  • repartition(n) before a write when you want n evenly sized files and the shuffle cost is small relative to downstream reads.
  • coalesce(n) after a filter that cut the data a lot, when n is still at least the number of cores you want busy and the surviving partitions are roughly even.
  • coalesce(1) to produce a single file, but know that one task reads all upstream partitions; if that's 30 GB it will OOM or take forever. repartition(1) shuffles first, so the read is parallel, but the final task still does all the work; neither is free.

Failure modes to name:

  • coalesce below core count → idle executors; the job runs at the task count, not the cluster size.
  • coalesce(1) on a large dataset → single-task OOM or a multi-hour tail.
  • repartition(200) on 2 GB → 200 tasks of 10 MB each, 200 tiny output files, scheduler overhead dominates.
  • Either one used to hide a hot key: coalesce spreads the hot partition's cost across fewer tasks, repartition keeps the skew in one partition. AQE skew join (skewedPartitionThresholdInBytes = 256 MB, skewedPartitionFactor = 5.0) splits it; neither repartition nor coalesce does.

Check: read the physical plan for Exchange vs Coalesce, count tasks in the stage, look at the shuffle read size distribution (max vs median), and count output files. A 10x gap between max and median shuffle read is the skew signal.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

A Spark job's stages are spending most of their time in shuffle write and fetch, with spill to disk on the map side. Walk me through how you'd diagnose it and which changes reduce shuffle volume and disk I/O without changing the result.

Answer

I'd confirm it's shuffle-bound, not CPU or GC. In the Spark UI Stages tab I look at shuffle write size, spill (memory/disk), shuffle read size and fetch wait time. If spill is non-zero and fetch wait is more than about 20% of task time, the bottleneck is shuffle. Then I'd read the physical plan for Exchange nodes, join strategy, partition count and skew. The changes that preserve the result are: eliminate the shuffle (broadcast join, bucketing), reduce data before shuffle (filter/project, map-side combine), reduce partition count via AQE coalesce, compress shuffle and spill, and tune fetch buffers. I'd verify by re-running on the same input and comparing output checksums and row counts.

Diagnosis. The SQL tab shows the plan; Stages tab shows Shuffle Write Size, Shuffle Read Size, Shuffle Spill (Memory), Shuffle Spill (Disk) and Fetch Wait Time. Task metrics expose shuffleWriteMetrics, shuffleReadMetrics, memoryBytesSpilled and diskBytesSpilled. Map-side spill means execution memory cannot hold the sort or aggregation state, usually because partitions are too few or the aggregation is not combining early. Fetch failures surface as FetchFailedException in driver logs; causes include executor loss (shuffle files gone), network timeout, too many concurrent fetches, corrupted shuffle files or a full disk. With dynamic allocation, enable the external shuffle service (spark.shuffle.service.enabled=true) so shuffle files survive executor removal.

Result-preserving changes:

  1. Broadcast join. If one side is under spark.sql.autoBroadcastJoinThreshold (default 10MB), Spark broadcasts it and the join needs no shuffle. Check table statistics with ANALYZE TABLE before relying on it.
  2. Bucketing. Pre-partition both tables by the join key with the same bucket count: CREATE TABLE ... CLUSTERED BY (key) INTO N BUCKETS. Spark then avoids the shuffle on that join.
  3. Filter and project early. Predicate pushdown and column pruning reduce the bytes that reach the shuffle.
  4. Map-side combine. Use reduceByKey instead of groupByKey, or aggregateByKey; in SQL, partial aggregation before the shuffle.
  5. AQE. spark.sql.adaptive.enabled=true (default true in Spark 3.2+). spark.sql.adaptive.coalescePartitions.enabled=true (default true) coalesces small partitions toward spark.sql.adaptive.advisoryPartitionSizeInBytes (default 64MB). spark.sql.adaptive.skewJoin.enabled=true (default true) splits skewed partitions.
  6. Compression. spark.shuffle.compress=true and spark.shuffle.spill.compress=true are defaults; spark.io.compression.codec=zstd can cut disk I/O further at some CPU cost.
  7. Buffer tuning. spark.shuffle.file.buffer (default 32k) to 64k or 128k; spark.reducer.maxSizeInFlight (default 48m) to 96m; spark.shuffle.io.maxRetries (default 3) and spark.shuffle.io.retryWait (default 5s) for flaky fetch paths.
  8. Partition count. spark.sql.shuffle.partitions defaults to 200. Too few partitions cause spill; too many cause fetch overhead. AQE coalesces after the shuffle, so a higher initial count is often safe.

Worked trace (hypothetical). A 1TB Parquet join on user_id followed by groupBy(user_id).sum(amount) shows shuffle write 800GB, disk spill 300GB, fetch wait 45% of task time, 200 partitions. After broadcasting an 8MB dimension table, switching to partial aggregation, enabling AQE coalesce to about 80 partitions of 64MB, and using zstd, shuffle write drops to 120GB, spill to 0, fetch wait to 8%. Output row count and per-user sums match the original.

SymptomLikely causeCheckFix (result-preserving)
Shuffle spill (disk) > 0Too few partitions or large aggregation stateStages tab spill metrics; partition countIncrease partitions or AQE coalesce; map-side combine
Fetch wait > 20%Too many small partitions or networkShuffle read size, fetch waitAQE coalesce; increase spark.reducer.maxSizeInFlight
FetchFailedExceptionExecutor lost, timeout, disk fullDriver and executor logs; shuffle serviceExternal shuffle service; increase retries/timeouts
Shuffle write largeUnnecessary shuffle (join, groupByKey)SQL plan Exchange nodesBroadcast join, bucketing, reduceByKey

python spark.conf.set("spark.sql.adaptive.enabled", "true") spark.conf.set("spark.sql.adaptive.coalescePartitions.enabled", "true") spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes", "64m") spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true") spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "10m") spark.conf.set("spark.shuffle.compress", "true") spark.conf.set("spark.shuffle.spill.compress", "true") spark.conf.set("spark.io.compression.codec", "zstd")

Checked against Spark 3.5.

Failure modes. A broadcast join OOMs if the small side grows past the threshold; detect it from driver/executor OOMs and table stats. Bucketing only avoids a shuffle when both sides use the same bucketing spec and join key. AQE coalesce can reduce parallelism too far if partitions are skewed; skew join handles that. Compression adds CPU, so it can hurt a CPU-bound job. Fetch failures from executor loss need the external shuffle service, not just retry tuning.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Choose a partitioning strategy for a large data pipeline.

Answer

What I'd say first

Assume a batch Spark job reading Parquet from a lake: 2 TB per run, 50 executors × 4 cores = 200 cores, target ~5 minutes per task. Partition count is derived, not chosen by taste:

partitions ≈ shuffle_bytes / (per_core_throughput × target_task_seconds)

At ~30 MB/s per core for scan-plus-shuffle, one task in 300 s moves ~9 GB, so 2 TB needs ~230 partitions. The Spark default spark.sql.shuffle.partitions=200 is therefore fine at this size, and that is the point: the default is not wrong, it is unexamined. It becomes wrong the moment the input grows 10× and nobody changes it.

Why skew happens, and how you see it

A shuffle writes one file per map task per reducer; each reducer reads its slice. If one key holds 30% of rows, 30% of shuffle bytes land on one reducer and that task runs ~N× the median. Stage wall time is the max task, not the mean, so 10× skew wastes ~90% of the cluster while the UI shows a healthy average.

Detection is a ratio, not a feeling: in the Spark UI stage detail, compare max task duration to the median. Above ~5× you have skew. Spark's AQE skew join uses the same shape, spark.sql.adaptive.skewJoin.skewedPartitionFactor=5 and skewedPartitionThresholdInBytes=256 MB, and splits partitions that cross both.

Defaults worth knowing (Spark 3.2+, where AQE is on by default)

settingdefaultwhat it controls
spark.sql.shuffle.partitions200post-shuffle partition count
spark.sql.files.maxPartitionBytes128 MBread-side split size
spark.sql.adaptive.advisoryPartitionSizeInBytes64 MBAQE target partition size
spark.sql.adaptive.coalescePartitions.enabledtruemerges small post-shuffle partitions
hive.exec.reducers.bytes.per.reducer256 MBHive reducer sizing

When to partition on a key

Only when a downstream operator reuses the distribution. If three joins all key on user_id, bucketing by user_id pays the shuffle once and skips it three times. If the next join is on session_id, you paid a shuffle for nothing. The test: does the same key appear in a join or groupBy more than once downstream? If not, let the engine shuffle.

Python
# reuse: bucket once, join many times
df.write.bucketBy(256, "user_id").saveAsTable("events_b")
# no reuse: leave it to AQE
df.groupBy("session_id").count()

Failure modes and their signals

  • Skew: max/median task duration > 5× in the stage view. Cost: stage time equals the slowest task.
  • Tiny files: average output file < 128 MB and file count climbing per run. Cost: ~ms of open+list per file; 20k files per day is a metadata problem, not a storage one.
  • Over-partitioning: 100k tasks × ~5 ms launch overhead ≈ 500 s of pure scheduling before any work.
  • Wrong bucket key: shuffle paid twice, no reuse. Visible as two identical Exchange nodes in the plan.

Decision point

If the input is under ~1 TB and no key repeats downstream, keep the default and let AQE coalesce. If a key repeats in joins, bucket on it. If max/median task duration exceeds 5×, fix skew before touching partition count: more partitions do not help a single hot key.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Select a join strategy for two large datasets.

Answer

Assumptions I would state first: Spark 3.5, two large Parquet datasets on object storage, an equi-join on a surrogate key, output feeding a downstream aggregate. If the join were non-equi or range-based, a broadcast inner side plus sort-merge is the only distributed option, and I would say so and stop.

Core answer. For two genuinely large sides I default to a sort-merge join with adaptive query execution on, and I broadcast only when the build side, after every filter has been applied, is measured to fit on each executor with margin. The decision turns on post-filter build-side size, key skew, and whether both sides are already distributed compatibly with the join key.

Build side after filtersStrategyWhy
Small, well under the thresholdBroadcast hash joinThe large side never moves; the shuffle is the entire cost
Tens to a few hundred MB, executors have headroomRaise spark.sql.autoBroadcastJoinThreshold (default 10MB) and broadcastStill cheaper than moving hundreds of GB
Both sides hundreds of GB to TBSort-merge join, AQE onBounded per-partition memory, spills to disk instead of OOM
Both sides bucketed on the key, same bucket countBucket join, no exchangeEliminates the shuffle altogether

Arithmetic for one case. A 2TB fact and a 400GB dimension, joined on user_id. Filtering the fact to 90 days leaves 300GB; at 2000 shuffle partitions that is about 150MB per task. Sort-merge exchanges 300GB + 400GB = 700GB across the network before sorting. The same join as a broadcast would need the 400GB dimension resident on every executor, which no cluster does. Flip it: the dimension filtered by country is 200MB on disk. With spark.executor.memory=8g and memoryFraction 0.6, roughly 4.8GB is available for execution and storage. A 200MB Parquet file deserializes larger, and the planner’s size estimate comes from file metadata, so I leave margin and raise the threshold to something like 250MB, keeping one broadcast in flight at a time.

Failure modes I name and how I detect them.

  • Broadcast that never lands. The driver builds and ships the relation before executors proceed. If that exceeds spark.sql.broadcastTimeout, 300 seconds by default, the stage dies with "Could not execute broadcast in 300 secs" and retries. Detection is the driver log or a broadcast exchange stage that stalls while tasks wait; the cost is a full stage retry plus driver memory pressure. The fix is to lower the threshold, or raise the timeout only when the size is genuinely justified.
  • Skewed partition OOM. One key holding 40% of rows lands in a single reducer that reads hundreds of times the median partition. Detection is the Spark UI task panel: max shuffle read versus median. When max exceeds five times the median and passes skewedPartitionThresholdInBytes (256MB default, skewedPartitionFactor 5), AQE splits it, provided spark.sql.adaptive.skewJoin.enabled is on: it has been default since 3.2. With AQE off you get executor OOM or shuffle fetch failures, and one long-tail task sets the stage wall clock.
  • A key that is not unique. A non-unique build key fans the join out; nulls in the key never satisfy an equi-join, so inner joins drop those rows silently while outer joins change semantics. Detection is comparing pre- and post-join counts against source aggregates per key.

Decision. Measure the build side after filters; broadcast it if it fits with margin, otherwise sort-merge with AQE coalescing and skew splitting enabled, then tune partitions toward the 64MB advisory target. Validate one skewed key and one duplicate-key case end to end before trusting the plan.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

When do you broadcast a small dimension table into a distributed join, and what do you do when the broadcast side grows past what an executor can hold?

Answer

Core (first 90 seconds). Broadcast the dimension when the build side is small enough that every executor can hold a full copy in heap and the shuffle it removes is large. The default gate is spark.sql.autoBroadcastJoinThreshold = 10485760 (10 MB), and it is compared against the optimizer's estimated in-memory size of the relation, not the Parquet bytes on disk. So check the estimate rather than trusting it: EXPLAIN the join and look for BroadcastHashJoin with a DataSize, or read the BroadcastExchange size in the SQL tab.

The trade is asymmetric. A broadcast join collects the build side to the driver, then ships one copy to every executor; the probe side is never shuffled. A sort-merge join shuffles both sides. Joining a 4 TB fact table to a 12 MB dimension, broadcast removes roughly 4 TB of shuffle write and read, minutes of wall clock and a large spill risk, for about 12 MB of heap per executor, call it 40 MB uncompressed. Obviously worth it. At 3 GB the same arithmetic gives 3 GB × 200 executors = 600 GB of cluster heap, plus a driver that must materialise the whole relation before it broadcasts anything. Not worth it, and no threshold change fixes it.

Broadcast hash joinSort-merge join
Shufflenone on the probe sideboth sides, by key
Per-executor memoryfull build side, replicatedone partition of each side
Drivercollects and holds the build sideholds only the plan
Spillsbuild side cannot spillspills to disk
Best whenbuild side ≪ executor heap, probe side hugeboth sides large, or build side unknown

Failure modes, and how you see them.

  • Driver OOM inside BroadcastExchangeExec's collect. The driver heap dies before any task runs: this is the first thing to break, not executor memory.
  • Executor OOM or GC-dominated tasks in the broadcast read path, visible as failed tasks with java.lang.OutOfMemoryError and GC time dominating the stage in the UI.
  • spark.sql.broadcastTimeout (default 300 s): "Could not execute broadcast in 300 secs" means the build side is too big to ship, not that the cluster is slow.
  • Stale or missing statistics. After a schema change or a partition added without ANALYZE TABLE, the estimate can be off by orders of magnitude: the plan says broadcast, the runtime says OOM.
  • Full outer equi-joins do not get a broadcast hash join at all; the planner falls back to sort-merge or a nested-loop join.

When it outgrows the executor.

  1. Shrink the build side first. Project only the columns the join and output need and pre-aggregate to the grain actually joined; a 3 GB dimension is often 300 MB afterwards.
  2. If it still does not fit, stop broadcasting. spark.sql.autoBroadcastJoinThreshold = -1 disables it and lets the planner choose sort-merge, which spills instead of dying.
  3. Bucket both sides by the join key (bucketBy(n, "key"), same n, saved as a table) so the join is shuffle-free without replication.
  4. Shard-and-union: split the dimension into k shards, broadcast shard i, union the k results. Each executor holds 1/k of the build side; you pay k scans of the fact side.
  5. For a genuinely large dimension joined every night, a co-partitioned bucketed table or an external lookup beats any per-job trick.

AQE note: spark.sql.adaptive.autoBroadcastJoinThreshold defaults to the static threshold and lets AQE convert a sort-merge join to broadcast at runtime using actual shuffle sizes. Useful, but it makes the plan vary run to run, and it will not rescue you when the build side is genuinely large.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Diagnose and fix a data-skewed join.

Answer

Assume Spark 3.x, a shuffle join between a large fact table and a dimension, and one stage where a few tasks run for tens of minutes while the median finishes in seconds. That gap is the symptom. Find the cause before changing anything.

Confirm it's skew, not a broken predicate. In the Spark UI, open the stage and compare the max task duration to the median, along with shuffle read bytes and spill. A workable rule: the slowest task running more than 5× the median and reading more than 256 MB of shuffle means a hot partition. Those are also the AQE defaults: spark.sql.adaptive.skewJoin.skewedPartitionFactor is 5.0 and skewedPartitionThresholdInBytes is 256 MB, with spark.sql.adaptive.enabled defaulting to true from Spark 3.2 and skewJoin.enabled true since 3.0.

Then separate the causes, because each needs a different fix. Pull the key distribution on both sides. Null or empty-string keys all hash to one partition: that's skew from bad data, not a hot customer. Duplicate keys on the dimension side cause fanout: the join output is larger than either input, and row-count reconciliation will show it. A predicate that isn't an equi-join, or a missing join key, turns into a cross product. Only after ruling those out is it a genuine hot key.

Now the fixes, cheapest first. Filter null and invalid keys before the shuffle: that alone often removes the worst partition. If one side is under spark.sql.autoBroadcastJoinThreshold, 10 MB by default, broadcast it and the shuffle disappears. If the hot side can be pre-aggregated to one row per key, do that before the join. Otherwise salt the hot keys: append a random suffix 0..N-1 to the hot keys on both sides and replicate the other side N times, then run a second aggregation to combine the partial results.

Worked example, hypothetical numbers. A 1-billion-row fact joins a dimension; one key is 30% of the rows. With 200 shuffle partitions, that key lands in one partition: 300 million rows, roughly 2.4 GB of shuffle read, and the task runs about 40 minutes against a 90-second median. Salt that key into 64 buckets and each bucket holds about 4.7 million rows: the task drops to roughly the median. The other side must be replicated 64×, so only salt when the other side is small enough to afford it.

Finally, verify correctness. Reconcile row counts and control totals between the skewed and fixed runs; a fast join that dropped or duplicated rows is worse than a slow one. Adding executors won't help: one hot partition is one task on one core. And re-check the tail after the fix, because the hot-key distribution moves as data grows.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design distributed aggregation for a high-cardinality dataset.

Answer

Assumptions I'd state first: batch aggregation over ~10 TB / 10^10 rows, group key with ~10^8 distinct values (high cardinality), consumer needs per-key count, sum, average, and a distinct-count estimate. Engine: Spark 3.5 on a shuffle-based cluster. If it's streaming instead, the same algebra applies but you add a dedup key and a watermark.

The decision: two-stage aggregation (map-side partial aggregation, shuffle by hash(group_key), reduce-side merge) with mergeable state, not partial answers. High cardinality changes the arithmetic: with 10^8 keys and 10^10 rows you average 100 rows/key, so a combiner cuts rows 10–100x but the shuffle still carries ~10^8–10^9 distinct-key rows. The shuffle payload is dominated by key count, not rows per key, so combiners help less than they do on low-cardinality data. Size partitions for that payload: at ~100 bytes/row, 10^9 rows is ~100 GB; with spark.sql.shuffle.partitions set so AQE's advisoryPartitionSizeInBytes (default 64 MB) yields ~1500–2000 partitions, each task holds ~50k keys. Small enough that the hash table stays in memory with spill headroom.

Mergeable state, not partial answers. Average is not associative over partial averages. Carry (sum, count); variance needs (sum, sum_of_squares, count) or a Welford merge. Trace: partition P1 = [10, 20, 30] → avg 20; P2 = [40] → avg 40. Averaging the averages gives 30; the true mean is 25. The (sum, count) merge gives (100, 4) → 25.

Python
from pyspark.sql import functions as F
# partial: mergeable (sum, count) per key — never average partials
partial = df.groupBy("key").agg(F.sum("value").alias("s"), F.count("value").alias("c"))
final = (partial.groupBy("key")
                .agg(F.sum("s").alias("s"), F.sum("c").alias("c"))
                .withColumn("avg", F.col("s") / F.col("c")))

Skew. A hot key (or all nulls collapsing to one group) sends one partition 100x the median. Detect it in the Spark UI: max task shuffle-read or duration vs the median across the stage. Fix by salting only the hot keys (split into N sub-keys, aggregate, then re-aggregate on the base key) rather than salting every key, which multiplies the shuffle by N.

Exact vs approximate. Pick from the consumer's error bound and label the output.

NeedMethodState / error
Exact count/sumfull shuffleO(distinct keys)
Distinct countHyperLogLog, m=2^14 registers~16 KB/sketch, ~0.81% std error (1.04/√m)
QuantilesKLL or t-digestfew KB, ~1% rank error
Heavy hittersCount-Min Sketchoverestimates, tunable width

Failure modes and detection. Null keys: group count collapses. Compare distinct groups to distinct non-null keys. Integer overflow: sum over int64 wraps. Cast to decimal or double and assert against an oracle. Duplicate delivery (streaming): non-idempotent sums double-count. Dedup on a key + watermark. Skew: max/median task ratio in the UI. Validate against an independent oracle on a sample, not by re-running the same job.

When not to do this: if the output is small and the input fits one node, a single-pass hash aggregation beats the shuffle entirely.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Decide whether to cache an intermediate result.

Answer

Clarify and assume

Two things decide this: how many actions read the result, and what it costs to recompute. Assume Spark 3.x, a batch job, and a result that comes out of a shuffle (join or aggregation).

Answer

Cache when recompute cost is high and reuse is more than one. A three-way join over 1.2 TB feeding three downstream actions: uncached, each action replays the join. Cached, you pay population once and read three times. Don't cache a DataFrame read once, or one that's a filter+select over Parquet: recomputing is cheaper than the memory you'd hold.

Size it before you pick a level. The storage pool per executor is spark.memory.fraction × spark.memory.storageFraction × heap = 0.6 × 0.5 = 30% of heap by default. At spark.executor.memory=8g that's ~2.4 GB per executor, ~9.6 GB across four.

Storage levels:

  • MEMORY_ONLY: fastest reads; partitions that don't fit are evicted and recomputed on next use. Only when the result fits with room to spare.
  • MEMORY_AND_DISK_SER: serialized (typically 2–4× smaller than deserialized objects), overflow spills to disk. The default choice for large results.
  • DISK_ONLY, when the shuffle needs the memory more than the cache does.

Worked example (hypothetical)

4 executors × 8 GB heap → 9.6 GB storage pool. The cached result serializes to 14 GB. With MEMORY_AND_DISK_SER: ~9.6 GB in memory, ~4.4 GB on disk. The SQL tab shows the upstream join+aggregate at 11 min per action; three actions = 33 min of recompute. Population is 3.5 min, plus disk reads for the spilled 4.4 GB. Net ~25 min saved. One action instead of three: population costs 3.5 min and saves nothing. Don't cache.

Failure modes

  • MEMORY_ONLY on a result bigger than the pool: partitions evicted, recomputed, and you pay both. Detect in the Storage tab: "Fraction Cached" below 100%, or the same stage reappearing in the SQL DAG.
  • Execution evicting storage: a later shuffle borrows the storage pool and drops cached blocks. Watch the Storage tab size fall mid-job.
  • GC pressure: deserialized cached objects in old gen cause long pauses. Check executor GC time in the UI; the _SER levels cut it.
  • Executor loss: cached partitions vanish and are recomputed from lineage. If lineage is long, that recompute is the whole job again.

What changes the decision

Reuse drops to one → don't cache. Result fits in memory → MEMORY_ONLY. Executors churn or lineage is long → checkpoint to HDFS truncates lineage, at the cost of a write; cache before checkpointing so it isn't computed twice. A big shuffle competing for memory → lower storageFraction or go DISK_ONLY.

cache() is lazy: the first action pays population. unpersist() when the downstream actions finish, or the blocks hold the pool for the rest of the job. And caching does not make a non-idempotent external write transactional: a retried task can still double-write.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Tune memory and executor sizing for a Spark workload.

Answer

What I'd say first (60–120s). I'd size from the task, not from the cluster. Take the largest shuffle stage, look at the Spark UI's task duration and shuffle-read/spill columns, and find the p50 and p99 task. If p99 bytes are within ~2× of p50, the stage is balanced and I size executors to hold one task's working set with headroom. If p99 is 10× p50, no heap size fixes it: that's skew, and I fix the key distribution or turn on AQE skew join before touching memory. Concretely, on Spark 3.5 with spark.executor.cores=4, I want each task's peak execution memory plus its share of cached data to fit inside the unified region, which for spark.executor.memory=10g is (10g − 300m) × 0.6 ≈ 5.8g (spark.memory.fraction=0.6, 300 MB reserved). Four tasks sharing 5.8g is ~1.4g each; if a task's sort buffer needs more, I either raise executor memory or drop cores to 2. I'd rather run 2 cores × 10g than 8 cores × 10g, because 8 concurrent tasks on one 5.8g pool spill constantly.

Why the numbers behave this way. Spark's unified memory is (heap − 300MB) × spark.memory.fraction, default 0.6, split by spark.memory.storageFraction=0.5 into a guaranteed-cache half and an execution half. Execution can borrow from storage and evict cached blocks; storage cannot evict execution. So a stage that caches a 4 GB table and then sorts will evict the cache and re-read it: that's the classic "cache hit rate dropped to 0 mid-job" symptom. Spill happens when a task's sort/aggregation buffer can't grow because the execution pool is exhausted by sibling tasks; the UI shows it as spark.sql.execution.sort.spill / shuffle spill bytes, and it turns a 40 ms task into 400 ms because every spilled record is a disk write plus a merge read.

Executor shape trade-off. Large executors (say 16 cores, 64g) amortize JVM startup and give big tasks room, but G1's pause scales with live-set size: a 64g heap with a 30g live set routinely shows 200–500 ms young pauses and multi-second mixed pauses, and losing one executor discards 16 tasks' work. Small executors (1 core, 2g) waste the ~384 MB overhead floor per executor and multiply shuffle fetch connections. The deciding rule: pick cores so executor.memory × 0.6 / cores ≥ the p99 task's peak execution bytes, and keep heap ≤ ~32g so compressed oops stay on and G1 pauses stay sub-200 ms. If a single task genuinely needs >8g, that's a sign to repartition, not to build a 128g executor.

Overhead and non-JVM memory. spark.executor.memoryOverhead defaults to max(384MB, 0.10 × spark.executor.memory). That 10% covers Netty shuffle buffers, thread stacks, and native allocations, but not PySpark. For Python workloads set spark.executor.pyspark.memory (or spark.python.worker.memory, default 512m) explicitly, or the container gets OOM-killed by the kernel while the JVM heap looks fine. Off-heap (spark.memory.offHeap.enabled=true, spark.memory.offHeap.size) moves execution memory out of GC's reach; it helps when GC fraction >10% but adds its own accounting and is off by default.

Failure modes and how I detect them. Spill: UI shuffle spill (memory) column > 0 and task time p99 ≫ p50. GC: -verbose:gc or the UI's GC time column; >10% of task time means heap pressure, not CPU. Skew: one task's shuffle read is >5× the median and spark.sql.adaptive.skewJoin.skewedPartitionFactor=5 / skewedPartitionThresholdInBytes=256MB didn't split it. Executor loss: spark.executor.heartbeatInterval=10s vs spark.network.timeout=120s; a lost executor with cached blocks forces recompute of its lineage. Container OOM: exit code 137 with heap well under limit points at overhead or Python workers.

What I'd change, in order. Fix skew first (AQE is on by default since 3.2; spark.sql.adaptive.advisoryPartitionSizeInBytes=64MB targets post-shuffle partition size). Then set spark.sql.shuffle.partitions (default 200) to roughly total_cores × 2–3 or let AQE coalesce. Then size executors to the p99 task. Then raise spark.executor.memoryOverhead if 137s persist. Then consider off-heap. I'd validate with a representative join + cache run and compare p99 task time, spill bytes, GC fraction, and cost per TB, not just wall clock.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design dynamic resource allocation for a shared cluster.

Answer

Assume Spark 3.5, and pin the cluster manager first because it decides how shuffle data survives executor removal: on YARN you run the external shuffle service (spark.shuffle.service.enabled=true), on Kubernetes there is no shuffle service so you enable shuffle tracking instead. My answer: dynamic allocation on, bounded by a floor that protects latency and a ceiling that protects neighbors, with timeouts derived from task duration rather than left at defaults.

How the manager actually decides. ExecutorAllocationManager polls the scheduler every 100 ms. If pending tasks exist and no request has gone out in the last spark.dynamicAllocation.schedulerBacklogTimeout (default 1s), it asks for executors, and the request size doubles each round (1, then 2, then 4) until it reaches maxExecutors. After the first round it waits spark.dynamicAllocation.sustainedSchedulerBacklogTimeout (default 1s) between rounds. That is what "sustained backlog" means: not one spike, but pending tasks still there after the previous request had time to land. Removal is the mirror image: an executor with no running tasks and no cached blocks for spark.dynamicAllocation.executorIdleTimeout (default 60s) is released. If it holds cached blocks, spark.dynamicAllocation.cachedExecutorIdleTimeout applies, and its default is infinity: cached executors are never released unless you set it.

Shuffle survival. With the external shuffle service, map output lives outside the executor, so releasing an executor costs nothing. Without it, shuffle tracking keeps any executor holding shuffle data until that shuffle is no longer needed, then releases it; spark.dynamicAllocation.shuffleTracking.timeout (default infinity) is the escape hatch for a shuffle that never unregisters.

Oscillation is arithmetic, not taste. If executorIdleTimeout is shorter than task duration, executors are released between waves and re-requested; a YARN container takes seconds to tens of seconds to come back, so the job stalls while the cluster churns. Rule: idle timeout ≥ 2–3× p95 task duration. With 30s tasks, 60s is marginal and 120s is safe.

PROPERTIES
spark.dynamicAllocation.enabled=true
spark.dynamicAllocation.minExecutors=4
spark.dynamicAllocation.initialExecutors=8
spark.dynamicAllocation.maxExecutors=200
spark.dynamicAllocation.executorIdleTimeout=120s
spark.dynamicAllocation.cachedExecutorIdleTimeout=600s
spark.dynamicAllocation.schedulerBacklogTimeout=2s
spark.dynamicAllocation.sustainedSchedulerBacklogTimeout=5s
spark.executor.cores=5
spark.decommission.enabled=true
spark.storage.decommission.shuffleBlocks.enabled=true
spark.scheduler.mode=FAIR

At 200 executors × 5 cores you have 1000 task slots; a 3000-task stage runs in three waves, and the doubling ramp reaches 200 in about eight rounds: roughly 8s of request time plus container startup, which is why minExecutors matters more than the ramp for latency-sensitive work.

When not to use it. Steady-load streaming jobs gain nothing and pay allocation latency plus shuffle-tracking bookkeeping: run them fixed-size. Latency-critical services should set minExecutors to the steady-state width so the first seconds of a burst are served at full width. Jobs that cache DataFrames heavily should set cachedExecutorIdleTimeout explicitly, because the infinity default makes maxExecutors the real cost ceiling.

Failure modes to watch. Shuffle fetch failures after removal show up as FetchFailedException and are recovered by re-running the map stage: expensive, so track them. Unbounded maxExecutors on a shared YARN queue starves neighbors; cap it and give tenants separate queues or FAIR pools with minShare and weight. Node drain without spark.storage.decommission.shuffleBlocks.enabled loses blocks mid-job. Admission-control heavy backfills rather than trusting elasticity to invent capacity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Use adaptive query execution safely.

Answer

What I'd say in the first 90 seconds

AQE is on by default since Spark 3.2 (spark.sql.adaptive.enabled=true), so the question is not whether to enable it but which of its decisions to trust. It is not one optimisation: it is a set of rules re-run at every shuffle boundary once the map side has finished, using measured map-output sizes instead of estimates. Three of them matter. CoalesceShufflePartitions merges post-shuffle partitions, OptimizeSkewedJoin splits oversized join partitions, and the broadcast rules can switch a join strategy at runtime. I run the first two deliberately, with sizes pinned to numbers measured from my own shuffles, and treat the third as a hazard to constrain rather than a win.

Assumptions: Spark 3.5, a batch job with a genuine shuffle (AQE only acts at exchange boundaries), and a shared cluster where occupancy beats the last few percent of a dedicated one.

Mechanism

Each ShuffleExchange becomes its own query stage. The map side runs first and reports MapOutputStatistics - compressed bytes and record counts per reduce partition. The reduce stage is planned only after that, so the inputs are measured, not estimated.

  • Coalescing merges a contiguous range of reduce partitions up to advisoryPartitionSizeInBytes (64 MiB default). Contiguity is the point: it keeps the local shuffle reader able to serve the data from the same executor.
  • Skew splitting is a conjunction. A partition qualifies only when it exceeds skewedPartitionFactor (5.0) times the median partition size of that stage, and also exceeds skewedPartitionThresholdInBytes (256 MiB).
  • A runtime broadcast is decided after both children have materialised. A broadcast planned statically spares the large side its shuffle entirely; the runtime conversion cannot undo a shuffle write that already happened, so it buys the join strategy, not the shuffle.

Worked on one stage: 200 reduce partitions and 3.0 GiB of shuffle write, so 15 MiB each. With parallelismFirst=false the coalescer targets 64 MiB: 3072 / 64 = 48 tasks, each carrying roughly 64 MiB. Now make one partition 900 MiB against a median of 40 MiB: 5 * 40 = 200 MiB, and 900 > 256, so it splits into chunks near the 64 MiB advisory size and the slowest reduce task drops from ~900 MiB into that ~64 MiB band. The cost is real - each chunk re-reads the non-skewed side's map output for that partition, so total shuffle read rises while the tail falls. Read both numbers off the stage, not by feel.

Pin these (Spark 3.5)

SettingDefaultDecides
spark.sql.adaptive.enabledtrue since 3.2master switch
spark.sql.adaptive.advisoryPartitionSizeInBytes64 MiBcoalescing target and skew chunk size
spark.sql.adaptive.coalescePartitions.parallelismFirsttruekeep parallelism over the target size
spark.sql.adaptive.coalescePartitions.minPartitionSize1 MiBfloor for a coalesced partition
spark.sql.adaptive.coalescePartitions.initialPartitionNumunset, falls back to spark.sql.shuffle.partitions (200)reduce count before the first coalesce
spark.sql.adaptive.skewJoin.skewedPartitionFactor5.0size against the median
spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes256 MiBabsolute floor for skew
spark.sql.adaptive.autoBroadcastJoinThresholdunset, falls back to spark.sql.autoBroadcastJoinThreshold (10 MiB)runtime broadcast
spark.sql.adaptive.localShuffleReader.enabledtrueread map output on the same executor, no network
spark.sql.planChangeLog.levelWARNset INFO to log which rule rewrote the plan

Where it goes wrong

  1. Coalescing eats your parallelism. 200 partitions across roughly 200 slots can coalesce down to 48, and now one slow executor stretches the stage. Symptom: stage wall time up while CPU stays flat, and the executed plan's AQEShuffleRead node reporting far fewer partitions than you have executors. Fix: raise coalescePartitions.minPartitionSize, or leave parallelismFirst=true.
  2. False skew. When most partitions are small, the median is small, so an ordinary 300 MiB partition satisfies both conditions and gets chopped. Symptom: many partial splits in the executed plan, shuffle-read bytes up, stage makespan unchanged. Fix: raise skewedPartitionFactor.
  3. Skew AQE cannot see. Splitting only applies to join partitions; a hot key inside a groupBy or distinct is untouched. Symptom: the aggregation stage still has one task several times the median while its input shows a plain coalesced read. Salting or a two-phase aggregate is the only fix.
  4. Runtime broadcast drift. Left unset, the adaptive threshold follows spark.sql.autoBroadcastJoinThreshold (10 MiB), so the plan you validated is not always the plan that runs. Set it explicitly, or to -1 to keep the decision static.

Validation I'd run

SCALA
// Spark 3.5, Scala
spark.conf.set("spark.sql.adaptive.coalescePartitions.parallelismFirst", "false")
spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes", "64m")
spark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionFactor", "5.0")
spark.conf.set("spark.sql.adaptive.autoBroadcastJoinThreshold", "10m")
spark.conf.set("spark.sql.planChangeLog.level", "INFO") // which rule rewrote the plan

def run(aqe: Boolean) = {
  spark.conf.set("spark.sql.adaptive.enabled", aqe.toString)
  spark.sql(q)
}
val on = run(true)
val off = run(false)
assert(on.exceptAll(off).isEmpty && off.exceptAll(on).isEmpty)

Run that against data shaped like production: a null-key block, an outer join, and one genuinely hot key that lands on a split boundary. Uniform synthetic data exercises none of the rules above, which is why "we tested it" and "we validated it" are different claims.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Handle the small-files problem in a distributed pipeline.

Answer

Assume an object-store table (S3, GCS, ADLS) written by Spark or Flink and read by Spark or Trino, with Iceberg, Delta or Hudi managing commits. Small files are a per-file overhead problem, not a bytes problem: every file costs a listing entry, a planning slot, an open, and usually a task. You pay that on every read until you compact.

The short answer: pick a target file size from how the reader behaves, then either write fewer, larger files up front or compact atomically afterwards, and never let compaction race writers.

Target sizes are not a matter of taste. Iceberg's write.target-file-size-bytes defaults to 512 MB; Hudi's hoodie.parquet.max.file.size defaults to 120 MB; an HDFS block is 128 MB. For Parquet on S3, 128–512 MB per file is the band most teams land in. Below that, per-file overhead dominates; above it, you lose parallelism and partition-pruning granularity.

Where the files come from: over-partitioned writes (one directory per hour per user), micro-batches that commit every minute, and task retries or speculation that each write their own file. Spark's spark.sql.shuffle.partitions defaults to 200, so a job that repartitions by a high-cardinality key can emit thousands of files per run.

Worked example. A streaming job commits every minute, 24 partitions, running 24 hours: 1,440 commits × 24 = 34,560 files/day. At ~2 MB each that is ~69 GB. A reader now opens 34,560 files; at 30–50 ms per S3 GET (illustrative), that is 17–29 minutes of open latency before any data is read, spread across tasks. Compacting to 128 MB gives ~552 files; to Iceberg's 512 MB default, ~138. The request bill is not the driver: 34,560 GETs at $0.0004 per 1,000 is about $0.014. Latency and planning are the cost.

Three levers, with what each costs:

leverhowprice
coalesce before writerepartition(n) / lower shuffle partitionsadds a shuffle, raises write latency
compact after writeIceberg rewrite_data_files, Delta OPTIMIZE, Hudi clusteringrereads and rewrites the data; needs an atomic commit
batch commitslonger micro-batch interval, or commit every N batchesraises end-to-end freshness latency

Spark's spark.sql.files.openCostInBytes (default 4 MB) lets one task pack several small files into a partition, which softens the read side but does nothing for listing or planning.

Failure modes. Concurrent compaction and writers without snapshot isolation lose or duplicate data. Iceberg, Delta and Hudi commit by swapping metadata atomically: Iceberg writes a new metadata.json and manifest list, Delta appends to _delta_log, Hudi advances its timeline, so compaction is a new snapshot and readers on the old one keep working. On raw Parquet plus Hive, a compaction that deletes and rewrites files is not atomic: a reader mid-job sees missing files. Over-compaction is the other failure: one 50 GB file per partition kills pruning and parallelism. And a retried or speculated task writing to a fixed filename duplicates files unless the writer uses the table's commit protocol.

Watch files per partition, the ratio below your target size, listing/planning time, compaction backlog, and bytes rewritten per day.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Investigate a distributed job whose last stage never seems to finish.

Answer

Start with the question that decides everything else: is the stage making progress, or is it wedged? Open the Spark UI, Stages tab, click the active stage. If the completed-task count is still climbing, even one task every few minutes, you have stragglers. If it has been frozen past the task timeout, you have a hang: a fetch-failure retry loop or a dead executor. Those two need opposite responses, so don't skip this step.

Assume Spark 3.5, AQE on (the default since 3.2), 4,000 tasks in the final stage. 3,996 done and 4 running is skew or one sick node. 2,000 done and 2,000 pending with no movement is scheduling: check the Executors tab for lost executors and the Environment tab for the resources the app actually got.

The number that decides the diagnosis is max-to-median task duration on the stage detail page. Spark prints 25th/50th/75th/max for duration, shuffle read, shuffle write, spill and peak execution memory. Max 10x the median with a flat median means skew. Max and median both high means something systemic: spill, GC, or a slow sink.

What the UI showsWhereLikely causeFirst move
4 tasks at 100x median shuffle readStage detail, Summary MetricsKey skewInspect partition sizes; salt or pre-aggregate
Every task slow, high disk spillStage detail, Spill (disk)Partition too large for memoryRaise spark.sql.shuffle.partitions (default 200) or executor memory
GC time > 10% of task timeExecutors tabHeap pressureDrop cached data or raise memory, not both
Repeated FetchFailedExceptionExecutor logsShuffle service or nodeCheck shuffle service and node health before killing anything
Tasks finish, stage never commitsStage detail, last taskSink throttlingCheck sink metrics; make writes idempotent

Put numbers on the skew before you act. 500 GB of shuffle across 4,000 tasks is ~125 MB per partition. If one key holds 40% of the data, that partition is 200 GB; at 50 MB/s that task runs ~67 minutes while its peers finish in about a minute. That is your straggler, and no amount of extra executors fixes it.

Now the trade-offs, with the criterion for each. Salting the hot key spreads the work but multiplies output partitions and needs a second aggregation: don't salt if the key is genuinely needed downstream without replication. AQE skew join is free and on by default, but it only fires on sort-merge joins when a partition exceeds 5x the median and 256 MB (skewedPartitionFactor, skewedPartitionThresholdInBytes); it will not rescue a groupBy with one monster key. Raising shuffle partitions fixes spill, but 200 → 4,000 means 4,000 small files and more scheduler overhead: wrong tool if the problem is one key. Speculative execution (spark.speculation, default false) masks a slow node but duplicates work and can double-write a non-idempotent sink; enable it only when the output is idempotent.

Failure modes to name out loud. Killing the stage to "restart" discards shuffle files and forces a full recompute: read the timeline first. Fetch failures that look like skew are often a decommissioned node; the retry (spark.shuffle.io.maxRetries, default 3, 5s apart) eventually gives up and the stage fails outright. And a stage that finishes all tasks but never commits is usually the sink throttling you, not Spark.

After recovery, reconcile: compare output row counts and checksums against the last good run. Then add an alert on max/median task duration ratio above 5, and a regression job with a deliberately skewed key so the next person sees it in CI, not at 3 a.m.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Make a distributed job correct under retries and speculation.

Answer

Assume a batch or streaming job with external side effects (writes to a database, object store, or message queue). The job must tolerate task retries, executor loss, driver recovery, and speculative execution. The core principle: separate computation from commit, and make the commit idempotent and atomic. Bind each execution to immutable input versions (e.g., S3 object version IDs, Kafka offsets, Iceberg snapshot IDs), schema, code/config hash, and a run identity. Make transformations deterministic where exact reproducibility matters: control time (use event time, not processing time), randomness (seed from a stable key), lookup versions (pin to a snapshot), and unordered reductions (sort by key before reducing). Stage outputs under a unique attempt/run path. Commit by atomically swapping a manifest that lists the complete set of output files. Deduplicate by a stable business/event key if the sink supports it. Clean abandoned attempts without deleting committed output. Reconcile accepted, rejected, and output populations. Test duplicate concurrent attempts, failure before and after side effect, lost acknowledgement, partial output, retry exhaustion, and rerun. Record which input and output version won.

A manifest commit is idempotent because the commit is a single atomic operation on a pointer. Retries either see the old manifest or the new one, never a partial set. For example, on HDFS, FileSystem.rename is atomic within the same filesystem. On S3, PutObject for a single manifest object is atomic. On Iceberg or Delta Lake, the metadata commit is atomic. If the sink lacks atomic commit, fall back to idempotent writes with a dedup key: the sink must support upsert or conditional writes (e.g., DynamoDB conditional put, Kafka idempotent producer). Speculation duplicates work; it is safe only if side effects are idempotent or disabled. Spark disables speculation by default (spark.speculation=false); if enabled, spark.speculation.multiplier=1.5 and spark.speculation.quantile=0.75 control when a task is speculated. Flink's exactly-once mode with TwoPhaseCommitSinkFunction provides transactional commit.

Trace: Attempt 1 writes attempt-1/part-0.parquet, attempt-1/part-1.parquet. Fails before commit. Attempt 2 writes attempt-2/part-0.parquet, attempt-2/part-1.parquet. Commits manifest-2 pointing to attempt-2 files. Attempt 1 retries: sees manifest-2 already committed, aborts, cleans attempt-1/. Speculative attempt 3 writes attempt-3/..., tries to commit, sees manifest-2, aborts.

Trade-offs: Atomic manifest commit vs. idempotent writes. Manifest commit requires a sink that supports atomic pointer swap (HDFS, Iceberg, Delta). Idempotent writes require a stable key and a state store for dedup, which adds memory and latency. Use manifest commit when you need exactly-once and the sink supports it; use idempotent writes when the sink is eventually consistent or lacks transactions. Speculation: enable only if tasks are pure or side effects are idempotent. If tasks perform unguarded external mutations, disable speculation or make mutations idempotent. Speculation increases resource usage and can cause duplicate side effects. Deterministic transforms: required for audit and reproducibility, but can be costly (e.g., sorting large datasets). If exact reproducibility is not needed, allow non-determinism but ensure idempotent commit.

Failure modes and detection: Duplicate concurrent attempts: both write to separate attempt paths; only one commits manifest. Detect via manifest version and attempt ID. Failure before side effect: no commit, safe. Failure after side effect but before commit: side effect may be visible; if sink is idempotent, retry overwrites; if not, need dedup or transactional sink. Lost acknowledgement: retry sees manifest already committed, aborts. Partial output: manifest commit prevents partial visibility. Retry exhaustion: job fails; reconcile counts. Rerun: new run identity, new manifest; old output remains until cleaned.

StrategyAtomic?Idempotent?Example systemsWhen to use
Temp + renameYes (HDFS)With existence checkHDFS, local FSSame filesystem, batch
Manifest object putYes (single object)YesS3, GCSObject store, batch
Transactional sinkYesYesKafka transactions, Flink 2PCStreaming, exactly-once
Idempotent writes + dedupNo (needs dedup)Yes (with key)DynamoDB, Cassandra, Kafka idempotent producerEventually consistent sinks

If the sink supports atomic commit, prefer manifest commit. If not, use idempotent writes with a stable key. If the job has no external side effects, speculation is safe and can reduce tail latency. If exact reproducibility is not required, relax determinism to improve performance.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Plan recovery from driver and executor failures.

Answer

Assumptions: Spark 3.5, cluster mode on YARN or Kubernetes, a batch job plus one Structured Streaming job, replayable sources (Kafka, S3). If the source is not replayable, everything below collapses to "checkpoint or lose data."

Core answer. These are two different problems. Executor loss is routine; Spark recovers it by recomputation, and your job is to make that recomputation cheap and bounded. Driver loss is not a Spark problem: the driver holds the DAGScheduler, MapOutputTracker, BlockManagerMaster and the streaming query state, none of it replicated. Recovery is an orchestrator restart plus a durable identity for the run, and the real risk is duplicated output, not lost work.

Executor loss. The driver declares an executor dead after spark.network.timeout = 120 s without a heartbeat (spark.executor.heartbeatInterval = 10 s). Cached blocks on it are gone and recompute lazily from lineage on next access: no scheduler action. Shuffle map outputs are tracked in the driver's MapOutputTracker; those (shuffleId, mapId) entries are marked unavailable. A reducer fetching one gets FetchFailedException after spark.shuffle.io.maxRetries = 3 attempts spaced spark.shuffle.io.retryWait = 5 s; DAGScheduler catches it and resubmits the map stage, recomputing only the missing partitions.

Retry budget: spark.task.maxFailures = 4 attempts per task; spark.stage.maxConsecutiveAttempts = 4 consecutive stage failures aborts the job. Blacklisting is off by default (spark.blacklist.enabled = false). Turn it on and spark.executor.maxFailedTasksPerExecutor = 10 blacklists an executor for the application, spark.blacklist.application.maxFailedExecutorsPerNode = 2 blacklists a node: that is what stops one bad node from burning the whole retry budget.

Decommission turns recompute into migration. spark.decommission.enabled is false by default; with it on, spark.storage.decommission.shuffleBlocks.enabled = true migrates shuffle blocks to peers or to spark.storage.decommission.fallbackStorage.path, while RDD blocks are not migrated (spark.storage.decommission.rddBlocks.enabled = false) and still recompute.

Why that matters, in numbers: an executor holding 8 shuffle blocks of 128 MB = 1 GB. Moving 1 GB over 1 Gbps is ~8 s. Recomputing it means re-reading the map stage's input: a 50 GB scan at 200 MB/s aggregate is 250 s. Decommission pays exactly when recompute costs far more than the network move.

Driver loss. On YARN the ApplicationMaster restarts up to spark.yarn.maxAppAttempts times (defaults to yarn.resourcemanager.am.max-attempts, 2); on Kubernetes the driver pod is not restarted unless a pod template sets a restart policy. Either way the new attempt re-runs from the start unless you gave it a durable identity: sc.setCheckpointDir for batch, checkpointLocation for streaming, which persists offsets and the state store (HDFS-backed by default, RocksDB via spark.sql.streaming.stateStore.providerClass) and retains spark.sql.streaming.minBatchesToRetain = 100 batches. Protect the driver too: spark.driver.maxResultSize defaults to 1 g, and a stray collect() past that kills it outright.

Output. The expensive failure is a driver crash between output commit and checkpoint commit. Make the sink idempotent: the file sink writes a _spark_metadata log and readers ignore files absent from it; Delta commits atomically to _delta_log and takes txnAppId/txnVersion so a replayed batch is a no-op; the Kafka sink uses transactions when checkpointLocation is set; foreachBatch hands you the batchId to key an upsert on. Without one of those, restart duplicates.

Checkpoint vs lineage. Recompute from lineage when the source is replayable and the upstream chain is short. Checkpoint when the chain is long, the source is not replayable, or you have a hard RTO. Lineage costs no storage but unbounded recovery time; checkpointing costs I/O and storage and bounds recovery to the checkpoint interval. Decide by comparing recompute time against checkpoint write time.

failuredetected byrecoverybound
executor lost120 s heartbeat gaprecompute missing shuffle partitions; cached blocks lazyspark.task.maxFailures = 4, stage attempts = 4
node draineddecommission signalshuffle blocks migrated; RDD blocks recomputed~8 s per GB at 1 Gbps
driver crashorchestratorrestart with same run identityspark.yarn.maxAppAttempts = 2
crash after commitduplicate rows/filesidempotent sink (_spark_metadata, txnVersion)one replayed batch

Test these: worker drain mid-shuffle, fetch-failure storm after node loss, driver crash before and after commit, lost sink acknowledgement, corrupted checkpoint, retry exhaustion. Set RPO/RTO and an escalation path; infinite retry only hides the outage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do you achieve end-to-end exactly-once processing when consuming from an offset-based message queue into an ACID data lake table?

Answer

End-to-end exactly-once processing requires three distinct coordinated components: a replayable source with deterministic offsets, a deterministic stateful execution engine that tracks offsets alongside internal state checkpoints, and an idempotent or atomically transactional sink. In distributed systems, transport layers inherently provide at-least-once delivery; exactly-once semantics (EOS) are achieved through atomic commit coordination or idempotency, not magical zero-loss zero-retry networks.

The Coordination Architecture

[ Kafka / Replayable Queue ]
      | (Batch offsets: [1000..1999])
      v
[ Distributed Engine (Spark / Beam) ]
      |-- Read deterministic slice
      |-- Write data files to temp staging in object storage
      |-- Update state store checkpoint (WAL)
      v
[ ACID Sink Metadata Log ]
      Commit Transaction:
        - Data files added: [part-001.parquet, ...]
        - App metadata: { "queryId": "job_orders", "batchId": 42, "endOffset": 1999 }

Mechanism: Atomic State and Sink Synchronization

  1. Deterministic Offset Range Assignment: The driver or coordinator polls the queue (e.g., Kafka) for the latest available offsets per partition, locking in a static range for the batch (e.g., Topic A, Partition 0: offsets 1000 to 1999). This bounds the processing scope deterministically.

  2. Staged Execution with Speculation Safety: Executor tasks consume their assigned partition offset slices. Tasks write immutable Parquet/ORC data files to staging paths or directly to target directory paths with unique task attempt IDs. Speculative copies or retried task executions produce distinct file UUIDs, preventing file-system write contention.

  3. Transactional Commit with Metadata Checkpoint: Instead of committing consumer offsets back to the messaging cluster asynchronously, offset progress is coupled directly to the lakehouse storage transaction log (e.g., Delta Lake or Apache Iceberg transaction logs). During the engine's commit phase (such as Spark Structured Streaming's micro-batch commit or a Beam TwoPhaseCommit sink):

    • The driver constructs a commit action containing the staged data file paths.
    • The driver attaches an application transaction identifier containing { queryId, batchId, latestOffsets } to the table commit metadata.
    • The storage layer atomically commits the change via optimistic concurrency control (CAS write on metadata JSON or catalog pointer swap).
  4. Recovery Protocol: If the coordinator crashes prior to the catalog commit, no new data files are registered in the ACID snapshot; orphaned staged files are cleaned up via retention policies. On restart, the engine queries the lakehouse table's last committed transaction identifier. It discovers batch $N-1$ succeeded at offset 1999, so it initiates batch $N$ starting precisely at offset 2000, discarding uncommitted work without duplication or data loss.

Comparison of Sink Strategies

StrategyMechanismFailure ModeTrade-off
Idempotent Upsert (Merge/Upsert)Primary key deduplication via MERGE INTO targeting table.Hash collisions or silent overwrite if non-deterministic updates arrive out of order.High write amplification; requires reading target index/partitions before writing.
Atomic Append with Commit Log TrackingAppend-only files committed alongside consumer offset metadata in a single atomic log entry.Driver failure before metadata log swap leaves orphan files in object storage.Zero write amplification on ingestion; downstream compaction/retention sweeps needed.
Two-Phase Commit (2PC)Coordinator orchestrates prepare/commit across partitioned sinks.Unresolved in-doubt transactions lock sink resources if coordinator permanently dies.High latency overhead across checkpoints; sensitive to participant timeouts.

Critical Failure Modes and Mitigations

  • Non-deterministic Processing Logic: If pipelines utilize non-deterministic functions (e.g., current_timestamp(), non-seeded random values, or unkeyed distributed joins), task retries or speculative executions generate mismatched rows. Mitigation: Derive all row-level timestamps from message payload metadata or pass deterministic batch start timestamps via engine runtime variables.
  • Out-of-Order Retries across Micro-Batches: A failed batch $N$ retrying while an asynchronous job launcher initiates batch $N+1$. Mitigation: Lakehouse table transaction prerequisites enforce strict sequential versions; batch $N+1$ encounters a version conflict error and aborts until batch $N$ succeeds.
  • Orphaned File Accumulation: Task speculation and aborted commits leave unreferenced objects on S3/GCS. Mitigation: Schedule vacuum/orphan-cleanup jobs bounded by an expiration threshold safely greater than maximum task runtime (e.g., 24 hours).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How do you produce correct event-time windowed results from an out-of-order stream, and what happens to events that arrive after the watermark has passed?

Answer

Clarify, then assume. Is the stream keyed? What lateness does the business tolerate? Can the sink upsert by window key, or does it need retractions? Assume an unbounded keyed source with event timestamps, 5-minute fixed windows per key, and a sink that upserts idempotently on (key, window).

Core answer. Window by event time, never processing time. The watermark is the runner's assertion that no further elements with event time earlier than T will arrive; it is what lets a window close and emit. In Beam the watermark is a property of the PCollection, not of each key: for a keyed PCollection the effective watermark is the minimum across all inputs, so one slow or idle partition holds back every window downstream. Set the watermark lag from measured out-of-orderness (e.g., p99 lateness of 2 minutes) so results emit with bounded delay.

Late data is any element whose event time is before the current watermark. Three policies:

  1. Drop: cheapest, wrong if late events carry signal.
  2. Side output: route late elements to a separate sink for reconciliation. In Beam, tag them in a DoFn by inspecting PaneInfo.getTiming() == Timing.LATE.
  3. Allowed lateness: retain window state for a configured period after the watermark passes the window end; late elements inside that period re-fire the window. Once the watermark passes window_end + allowed_lateness, state is garbage-collected and further late elements are dropped.

Pick by correctness requirement and sink. Idempotent upsert (e.g., BigQuery MERGE on (key, window)) pairs with ACCUMULATING mode: each re-fire emits the full updated aggregate and overwrites. Append-only sinks need retractions, or DISCARDING mode plus a downstream aggregation, because a re-fire then emits only the delta. Note the default trigger AfterWatermark.pastEndOfWindow() fires once and does not re-fire: without a late firing trigger, late elements are never emitted even if state is retained.

Trace. FixedWindows(5 min), allowed lateness 10 min, watermark = max event time seen − 2 min.

processingelementevent timemax event timewatermarkeffect
10:01e110:0110:0109:59buffered in [10:00,10:05)
10:03e210:0310:0310:01buffered
10:07e410:0710:0710:05watermark reaches 10:05 → fire [10:00,10:05), sum=2
10:08e310:0410:0710:0510:04 < 10:05 → late; inside lateness → re-fire, sum=3
10:20e510:1810:1810:16watermark passes 10:15 → GC [10:00,10:05) state

Code (Beam Python).

Python
import apache_beam as beam
from apache_beam.transforms import trigger, window

(events
 | beam.WindowInto(
     window.FixedWindows(5 * 60),
     trigger=trigger.AfterWatermark(
         late=trigger.Repeatedly(trigger.AfterCount(1))),
     allowed_lateness=10 * 60,
     accumulation_mode=trigger.AccumulationMode.ACCUMULATING)
 | beam.CombinePerKey(sum))

Add an early trigger (AfterProcessingTime) if you want speculative panes before the watermark; they are superseded by the on-time firing.

Failure modes. Watermark lag too small → late events dropped, results undercount; detect via late-data counters and a batch recompute. Lag too large → high latency and unbounded state growth; watch watermark lag and state size. A skewed or idle partition stalls the minimum watermark and delays every window; watch per-partition watermark lag and enable idle-source advancement. A non-idempotent sink turns re-fires into duplicates; compare row counts against distinct window keys. Allowed lateness too short drops legitimate late data, too long pins state in memory.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Guarantee coherent output publication from many distributed tasks.

Answer

Clarify first. Three things decide the design: is the store POSIX (HDFS) or an object store (S3/GCS/ADLS)? Can two writers commit the same dataset concurrently? Must readers query while a run is in flight?

Assume an object store, many tasks, one logical writer per run but possibly overlapping runs, and readers querying continuously. Then the answer is a two-phase commit: tasks produce invisible immutable files, and one committer atomically flips a pointer.

The core answer

Never let a reader discover a task's output by listing the output directory. A task writes attempt-scoped files, data/<uuid>.parquet, that no manifest references yet, so they are invisible. When every task and every reconciliation check has passed, a single committer publishes a manifest (or table snapshot, or pointer file) naming the complete winning file set. The pointer swap is the only atomic step: everything before it is invisible, everything after it is visible.

Iceberg does exactly this. The driver writes a manifest list, then calls the catalog to swap the table's metadata_location with a compare-and-swap. If another writer committed first, the CAS fails and the commit retries: commit.retry.num-retries defaults to 4. Delta Lake does the same with a monotonically numbered JSON commit in _delta_log/, using put-if-absent; on S3 that needs a DynamoDB-backed LogStore, because S3 has no native CAS.

Reconciliation before the swap: per-partition row counts against the source watermark, null/range checks on key columns, and a SHA-256 plus row count recorded per file in the manifest. A partition that fails is quarantined, not published.

The commit sequence, with failure injection

stepactioncrash here →
1200 tasks write data/<uuid>.parquet, SHA-256 + row count recordedfiles orphaned, invisible
2task 17 fails, retried as attempt 1; attempt 0's files orphanedsame
3driver writes manifest-list.avro referencing 200 manifestsorphaned manifest list, invisible
4catalog CAS: swap metadata_locationno reader sees anything; re-run commit
5CAS succeeds; readers now see snapshot N+1commit already durable; retry is a no-op
6orphan GC after 3 days (remove_orphan_files default)—

Choosing a publication strategy

strategyatomic stepworks oncostwhen
task-rename committer (Spark FileOutputCommitter v1/v2)directory renameHDFS, where rename is atomicv1 = 2 renames/task; on S3 rename is copy+delete, O(data)HDFS, single writer
magic/multipart committer (S3ACommitter, Hadoop 3.3.1+)complete multipart uploads, write _SUCCESSS3no rename; uploads invisible until completedSpark jobs on S3
catalog CAS manifest (Iceberg/Delta/Hudi)pointer swapany store with CASextra catalog round-tripconcurrent writers, time travel, schema evolution

Failure modes

  • Committer crash before the pointer update. Nothing is visible; retry the commit. Orphans are cleaned by GC.
  • Crash after the pointer update, before acknowledgement. The commit is idempotent: re-issuing the CAS with the same expected metadata location fails, and you detect you already won. Never re-run the whole job.
  • Duplicate attempt. UUID-scoped names mean a retried task cannot overwrite a previous attempt's files.
  • Partial listing. Do not use LIST to decide completeness. S3 has been strongly consistent for LIST since December 2020, but S3-compatible stores and HDFS with stale readers may not be; the pointer is the source of truth.
  • Reader concurrency. A reader pins snapshot N; GC must not delete files still referenced by any live snapshot. Retention (Iceberg 3 days, Delta VACUUM 7 days) is the safety margin.

What would change the decision

If the store has no CAS, plain S3 without DynamoDB, you need an external lock or a single-writer guarantee. If you have one writer on HDFS, skip the manifest: write to a temp directory and rename it. If readers need sub-second freshness, the catalog round-trip and the GC window are the cost you are paying for coherence.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

You need to reprocess a historical window of data through a distributed pipeline while live data continues to flow. How do you make the backfill idempotent and keep downstream tables consistent?

Answer

Assume a 30-day backfill for a pipeline that normally processes live data into a partitioned table (e.g., events partitioned by dt). Live writes go to today's partition; backfill must rewrite dt from 2024-01-01 to 2024-01-30 without corrupting live reads or duplicating records.

Make the backfill idempotent by writing to a staging location keyed by the same deterministic primary key (e.g., event_id), then atomically swapping partitions. In Spark, set spark.sql.sources.partitionOverwriteMode=dynamic and write with mode("overwrite") to only replace the target partitions. This avoids touching live partitions and makes reruns safe: each run overwrites the same set of partitions with the same deterministic output. If the sink supports ACID (Delta, Iceberg, Hudi), use MERGE INTO on the primary key; reruns update existing rows instead of appending duplicates.

python spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic") df.write.mode("overwrite").partitionBy("dt").saveAsTable("events")

Keep downstream consistent by isolating backfill writes from live reads. Options:

StrategyIdempotent?Downstream consistencyWhen to use
Dynamic partition overwriteYes, if output deterministicReaders see old partition until swap completesBatch backfill, partitioned table
Staging table + atomic swapYesReaders see old table until swapNo ACID, need zero-downtime
MERGE/upsertYes, with keyReaders see mixed old/new rows during mergeACID sink, small updates
Shadow table + view swapYesReaders see old view until swapComplex transformations

For a 30-day backfill of 1 TB/day (30 TB total) against 100 GB/day live, the backfill is 300x live volume. Throttle it: run backfill in a separate YARN queue or Kubernetes namespace with fair scheduling, cap executor count, and schedule during low live traffic. Monitor shuffle spill and GC; historical data may be skewed differently.

Failure modes: a job crash mid-write leaves partial partitions. Dynamic overwrite is atomic per partition, but a multi-partition job can fail after some partitions are written. Use a run manifest (e.g., _SUCCESS per partition) and only swap after all partitions succeed. Duplicate keys from non-deterministic transformations (e.g., current_timestamp()) break idempotency: replace with event-time or a fixed backfill timestamp. Downstream readers during a MERGE can see inconsistent rows; use snapshot isolation or a view swap. Detect issues by comparing row counts and checksums per partition before and after, and alert on duplicate primary keys.

Alternatives: if the downstream is a streaming job, write backfill to a side table and run a compaction job that merges into the live table with a watermark. If the pipeline is Beam, use FileIO with a temp directory and atomic rename, and Deduplicate on the key. MapReduce jobs achieve idempotency by writing to a new output directory and renaming on success.

The key is: deterministic output + atomic visibility + isolation from live traffic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design a distributed pipeline with expensive external API enrichment.

Answer

What I say first

Four answers change this design: does the vendor have a batch endpoint, what is the per-account rate limit and per-call price, does it honor an idempotency key, and how stale can the enriched field be. Assume 8M records/day, a per-record endpoint capped at 50 rps at $0.01/call, a batch endpoint taking 100 IDs per call at $0.006/ID, a vendor p99 of 800 ms, idempotency keys honored, 24h freshness acceptable, strict tenant isolation.

I'd build two stages. Ingest and validation are deterministic and cheap. Enrichment is the only stage touching an external dependency, so it runs behind a durable queue with bounded concurrency, a stable idempotency key, a retry taxonomy and a breaker. Isolating it means a vendor outage grows a queue instead of stalling ingest.

Batch beats per-record, and the arithmetic decides it

8,000,000 records/day on a per-record endpoint is 8,000,000 / 86,400 = 92.6 rps average, 370 rps at a 4x peak, against a 50 rps cap. Most calls get 429, backoff pushes the backlog further out, and the daily job never closes: 8,000,000 / 50 = 160,000 s = 44.4 h. Batching 100 IDs per call gives 80,000 calls/day = 0.93 rps average, 3.7 rps at peak. Cost: 8,000,000 * $0.01 = $80,000/day per-record versus 8,000,000 * $0.006 = $48,000/day batched. If the vendor has no batch endpoint, replicate the enriched table on a schedule and use per-record calls only for misses.

Concurrency, breaker, autoscaling

Global semaphore at 40 in-flight requests: 80% of the 50 rps quota, leaving headroom for retries. Per-tenant cap at 8, so one tenant's backfill can't eat the whole allowance; without per-tenant limits a single 1M-record backfill starves everyone else on the account.

Breaker opens when error rate exceeds 50% over a 60 s rolling window with at least 20 requests, and half-opens on 5 probes. While it's open, pause dequeue and hold the autoscaler at its floor. Scaling on queue depth with the breaker open is what turns a vendor blip into an outage: more workers mean more 429s, and the vendor's limiter extends the penalty for every tenant on your account. Client deadline is 2.0 s against a vendor p99 of 800 ms, and shorter than the queue visibility timeout so a wedged message redelivers rather than vanishing.

Idempotency and retry classification

Key = sha256(tenant | record_id | vendor_version), constant across attempts, sent as the vendor's idempotency header.

Python
VENDOR_VERSION = "2024-06"

def enrich(rec, tenant):
    key = sha256(f"{tenant}|{rec.id}|{VENDOR_VERSION}".encode()).hexdigest()
    for attempt in range(3):
        try:
            return vendor.lookup(rec.id, idempotency_key=key, timeout=2.0)
        except (Timeout, RateLimited, ServerError):
            if attempt == 2 or retry_budget_exhausted(tenant):
                quarantine(rec, "retryable_exhausted"); return
            time.sleep(random.uniform(0, 0.2 * 2 ** attempt))
        except ClientError as err:          # 400/404/422
            quarantine(rec, type(err).__name__); return

Trace it: attempt 0 timed out, slept a random 0-0.2 s; attempt 1 got 429, slept a random 0-0.4 s; attempt 2 timed out and quarantined. Three vendor calls, one effect, because the key never changed. A 422 on attempt 0 goes straight to quarantine, no retry. Retry budget caps retries at 10% of a tenant's throughput so a wide outage can't grow the queue without bound.

Cache, deletion, failure modes

Cache keyed on (tenant, record_id, vendor_version) with a 24h TTL matching the freshness contract. On tenant erasure, delete by tenant prefix: it's a lookup store with deletion semantics, not an append-only log. If the contract forbids persisting responses, use an in-process cache with a 15-minute TTL instead.

failuredetectionaction
timeout after remote successvendor call count > local first-attempt countidempotency key, no duplicate effect
throttling429s exceed 1% of calls over 60 scut concurrency 25%, double base backoff
partial vendor outagebreaker > 50% errors with >= 20 requests in 60 sopen breaker, pause dequeue, page on-call
vendor schema changeunknown-field ratio > 0 in the contract test against a recorded fixturepin VENDOR_VERSION, quarantine the batch

Reconcile daily per tenant: enriched + quarantined + rejected must equal input. That equality is what catches silent drops.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Operate a distributed job during a dependency outage.

Answer

Assumptions I'd state before touching anything: the job is a checkpointed task graph with idempotent tasks, it writes a versioned output that consumers read, and it has a freshness SLA. The dependency is a remote service I don't control.

First 90 seconds. Stop admitting new work, keep the last good output published, and classify the failure before changing any retry setting. Retrying a 401 or a 422 is pure load with no chance of success; retrying a 503 is the entire point. Classification decides everything downstream.

ClassSignalAction
Transient5xx, connection reset, p99 latency spikeRetry with backoff, keep checkpoint
Throttling429, Retry-After headerHonour Retry-After, drop concurrency, never retry faster
Auth401/403, uniform fast failuresStop retrying, page the credential owner
Corrupt input400/422 clustered on a key rangeQuarantine those records, continue the rest
Permanent404, schema mismatch, deterministic per recordFail the partition, do not retry

Bound the retries. Settings I'd start from: base 500 ms, factor 2, cap 30 s, full jitter. Sleep uniform in [0, 500 ms], [0, 1 s], [0, 2 s], and so on, so six attempts spend roughly 31 s sleeping rather than 31 s hammering. A retry budget of 10% of successful calls per minute per client, and a breaker that opens after 20 consecutive failures or a >50% failure rate over a 30 s window with at least 20 requests, then half-opens with a single probe after 30 s. The number that actually matters is aggregate: 200 workers × 6 retries is 1200 extra calls, so cap in-flight retries at about 10% of steady-state concurrency, not per worker.

Resume or rerun. Resume from the last validated checkpoint when the checkpoint is durable, tasks are idempotent, and writes are keyed so a replay overwrites rather than duplicates. Rerun from scratch when the checkpoint predates a schema change, when partial writes can't be reconciled against the source, or when the outage corrupted the state the checkpoint depends on. The cost is concrete: resuming a 4-hour job with 40 minutes left costs 40 minutes of compute; a full rerun costs 4 hours, so rerun only when you can't trust the boundary.

Failure modes and how you see them. Retry storm: your retry rate rises and the dependency's error rate rises with it; the breaker and the aggregate cap are the fix. Thundering herd on recovery: retries land on the same second because jitter was dropped; watch the retry timestamp histogram. Lost acknowledgement: the task succeeded but the ack was lost, so it replays; detect duplicate idempotency keys. Checkpoint written before the side effect: detect by reconciling output counts against source counts after recovery. Stale output served as fresh: detect with a freshness metric on the published version, not on the run's status.

Communicate. Mark the run delayed with the last-good timestamp, the affected partitions, and an ETA of unknown rather than a guess. Never publish a partial dataset as complete; a consumer that reads a half-written partition and caches it is worse than one that reads yesterday's data. Quarantine deterministic bad records separately from infrastructure failures so the two don't get reconciled together.

After recovery, resume from the validated boundary, reconcile the full output, and watch catch-up load so backfill doesn't starve live work. Then record the timeline, the decisions, and the residual gaps.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Optimize a job without compromising correctness.

Answer

What I'd say first

Optimization is a controlled experiment with a correctness gate, not a settings sweep. Three things come before any config change: a frozen input, a stated objective, and a baseline.

Freeze the input snapshot (say the event_date = 2024-03-01 partition, 1.8 TB Parquet) and pin the expected output as a row count and a checksum and a per-column null count and SUM(CAST(amount AS DECIMAL(18,4))). Row count alone misses dropped duplicates; a checksum alone misses reordering. Name the objective as a number: "p99 stage duration under 12 minutes at 400 concurrent slots" or "$0.42 per run". Without it every change is arguable.

Baseline from EXPLAIN FORMATTED plus the Spark UI stage table: per-task shuffle read/write, disk and memory spill, GC time, task-duration percentiles, retry count. The bottleneck is whichever of those dominates, and it is usually one of: scan, shuffle, skew, serialization, spill/GC, scheduling, driver, sink.

Spark 3.5 defaults worth knowing before you touch anything

  • spark.sql.shuffle.partitions = 200
  • spark.sql.autoBroadcastJoinThreshold = 10 MB
  • spark.sql.adaptive.enabled = true; spark.sql.adaptive.coalescePartitions.enabled = true
  • spark.sql.adaptive.advisoryPartitionSizeInBytes = 64 MB, but spark.sql.adaptive.coalescePartitions.parallelismFirst defaults to true, which makes coalescing target the 1 MB minPartitionSize instead. Set it false to actually get 64 MB partitions.
  • spark.sql.adaptive.skewJoin.enabled = true, skewedPartitionFactor = 5, skewedPartitionThresholdInBytes = 256 MB
  • spark.sql.files.maxPartitionBytes = 128 MB

Worked trace

Job: 1.8 TB Parquet scan → join a 12 GB dim on user_id → group by user_id. 200 shuffle partitions, 900 GB shuffle write.

  • 900 GB / 200 = 4.5 GB per reduce partition. If the baseline shows ~50 MB/s of shuffle read per task, that is ~90 s per task before any spill. Set spark.sql.shuffle.partitions = 8192 → 900 GB / 8192 ≈ 112 MB per partition. With parallelismFirst=false and the 64 MB advisory, AQE coalesces the small ones back up.
  • Skew: if one user_id (a bot account) holds 40 GB and the median partition is 300 MB, the factor is ≈137 > 5 and 40 GB > 256 MB, so AQE splits it. With AQE off, salt it, concat(user_id, '_', floor(rand()*16)), and explode the dim 16×.
  • Broadcast: 12 GB is ~1200× the 10 MB threshold, so do not broadcast it. At 8 MB the threshold already handles it; forcing /*+ BROADCAST(dim) */ on 12 GB OOMs the driver.

Correctness gate

Re-run the frozen input and compare row count, null counts and the decimal sum. Kill one executor mid-shuffle and confirm the checksum is unchanged, so the retry path is covered. Reject anything that drops records, shifts decimal scale, or reads a cache that is not invalidated.

Failure modes

  • AQE coalescing to 1 MB partitions because parallelismFirst was left at its default: thousands of tiny tasks and scheduler overhead dominates.
  • A skew split that still leaves one side above the 256 MB threshold.
  • A broadcast hint on a table that outgrew the threshold since the last run: driver OOM, not a slow job.

If the job already meets its SLO, leave it alone. If the baseline shows the scan dominating and shuffle is small, partition pruning, compaction or Z-ordering beats any shuffle tuning.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Test a distributed data-processing job before production.

Answer

What I'd say first

The job's contract is three things: same input gives the same output, it finishes inside its resource envelope, and a retry doesn't double-write. So I test in tiers, cheapest first, and the tier I stop at is decided by two properties of the job: whether the sink is idempotent, and whether the input is skewed.

Assume Spark 3.5 writing Parquet to S3 behind an Iceberg catalog, batch, ~1 TB per run. If the sink is a plain append-only prefix instead, the failure tier becomes mandatory rather than optional.

Tier 1: semantics, on one machine. Pure transforms get unit tests with hand-built fixtures. Then I compare the whole output against an independent oracle, a pandas or SQL reimplementation, not a few spot rows. The cases that actually break jobs: empty input, all-null keys, duplicate keys, late-arriving rows, and a many-to-many join that fans out. The oracle check is a full-outer join on the key:

Python
# PySpark 3.5
a = actual.groupBy("k").agg(F.sum("amt").alias("amt"))
e = expected.groupBy("k").agg(F.sum("amt").alias("amt"))
diff = (a.alias("a").join(e.alias("e"), "k", "full_outer")
        .where(F.col("a.amt").isNull() | F.col("e.amt").isNull()
               | (F.col("a.amt") != F.col("e.amt"))))

A key present in both with equal sums drops out; a key only in actual keeps its row because e.amt is null. Empty diff is the pass condition.

Tier 2: integration. Real file formats, real catalog, schema evolution (add a column, then read the old partitions back), partition discovery, and the sink's commit path.

Tier 3: cluster, production-shaped. This is where skew shows up. Why: the shuffle hash-partitions on the key, so one key holding 30% of rows sends 30% of the data to a single task. With the default spark.sql.shuffle.partitions=200 and a 1 TB shuffle, the average partition is 5 GB, but the hot one is 300 GB, blows past executor memory, and spills to spark.local.dir. You see it as Shuffle Spill (Disk) in the SQL tab and a p99 task time far above the median. AQE's skew handling (skewedPartitionFactor=5.0, skewedPartitionThresholdInBytes=256MB) splits that partition, but only when AQE is on and the join is sort-merge.

Tier 4: failure injection. Kill an executor mid-shuffle; kill the driver after tasks finish but before commit; make one worker slow; fail a fetch; force a speculative attempt. What each exposes: a partial commit is invisible with Iceberg, because the catalog commit is atomic (readers see the old snapshot or the new one, never half) but with a plain S3 prefix plus Hive-style partitions a reader sees half the files. A duplicate attempt is harmless if the write is a MERGE on a natural key and fatal if it's an append. That append-vs-merge distinction is the single most common production bug in this class of job.

Trade-offs. If the sink is idempotent and the input is bounded and balanced, tiers 1 and 2 plus a 1 GB cluster smoke test are enough; a full-scale run buys you little. If the sink is append-only, or one key dominates, you need tiers 3 and 4, and you should budget for them, because a 1 TB shuffle across 100 executors is real money and a real hour. The decision rule: idempotent sink plus balanced input → sample; anything else → production-shaped.

What would change my answer: a streaming job, where the equivalent of tier 3 is a checkpoint-and-restart test and the duplicate question becomes "does the sink dedupe on the event key."

Curated: · Written: · Reviewed:

Difficulty: Hard