Spark and Hadoop interview questions: architecture, shuffles and tuning
Spark interview questions check whether you can explain what happens between writing a DataFrame query and getting a result: the driver builds a plan, wide transformations split it into stages at shuffle boundaries, and executors run one task per partition. Expect questions on lazy evaluation, RDDs versus DataFrames, partitioning, data skew, broadcast joins, caching and Structured Streaming, with Hadoop's HDFS, YARN and MapReduce asked as background. Strong answers connect each concept to something you would see in the Spark UI.
By Evin JohnPublished 10 min read
How Spark and big data questions show up
Spark appears in data engineering, analytics engineering, machine learning platform and backend roles that touch large batch or streaming pipelines. A typical loop has a concept round (architecture, execution model, file formats), a hands-on round where you write PySpark or Spark SQL against a small dataset, and a scenario round built around a slow or failing job. Interviewers often hand you a screenshot of the Spark UI or a query plan and ask what is wrong. Hadoop questions are lighter now that most teams run Spark on Kubernetes or a managed platform, but HDFS and YARN still come up because many older clusters use them and because they explain where Spark's design came from.
Architecture and execution model
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What do the driver and executors each do? | Mental model | The driver runs your main program, builds the logical and physical plan, and schedules tasks. Executors are processes on worker nodes that run those tasks, hold cached data and write shuffle files. |
| What is a cluster manager in Spark? | Deployment | The service that hands out machines and memory: Spark standalone, Hadoop YARN or Kubernetes. Spark asks it for executors; it does not decide how your query runs. |
| Explain jobs, stages and tasks. | Execution vocabulary | Each action starts a job. The job splits into stages wherever a shuffle is needed. Each stage runs as many tasks as it has partitions, one task per partition per core slot. |
| What is the DAG and why does Spark build one? | Planning | A directed acyclic graph of the transformations that lead to a result. Seeing the whole graph lets Spark pipeline narrow steps together, place stage boundaries and recover lost partitions by recomputing from lineage. |
| Narrow versus wide transformations? | Shuffle awareness | Narrow ones (map, filter, select) need only one input partition per output partition. Wide ones (groupBy, join on unaligned keys, distinct, repartition) need data from many partitions, so rows move over the network. |
| What does lazy evaluation buy you? | Optimizer reasoning | Transformations only record a plan. When an action arrives, Spark can push filters down, prune columns, reorder joins and fuse steps before reading a single byte. |
| Name three actions and three transformations. | Basics | Actions: count, collect, write, show, take. Transformations: select, filter, withColumn, join, groupBy, union. The test is whether the candidate knows which ones trigger work. |
| How does Spark recover when an executor dies? | Fault tolerance | Tasks on that executor are retried elsewhere. Lost partitions are recomputed from lineage, and lost shuffle output forces the parent stage to rerun for the missing pieces. |
RDDs, DataFrames and Spark SQL
- RDD versus DataFrame versus Dataset? An RDD is a distributed collection of objects with no schema Spark can reason about. A DataFrame has named, typed columns, so the Catalyst optimizer can plan it. A Dataset adds compile-time types and exists only in Scala and Java; in Python you work with DataFrames.
- When would you still use an RDD? Rarely: for low-level control over partitioning of arbitrary objects, or legacy code. Most interviewers want to hear that DataFrames are the default because they are optimized and use compact binary storage.
- What does the Catalyst optimizer do? It turns your query into a logical plan, applies rule-based rewrites such as predicate pushdown and constant folding, picks physical operators (join types, aggregation strategy), and generates code for the chosen plan.
- What is Tungsten? The execution engine work that stores rows in a compact binary format (on or off the JVM heap) and generates JVM bytecode for whole stages, which avoids a lot of object creation and virtual calls.
- Why are Python UDFs slow, and what do you use instead? Each row is serialized out of the JVM to a Python worker and back, and the optimizer cannot see inside the function. Prefer built-in functions; if you need Python, use a pandas UDF, which moves data in Arrow batches.
- How do you read a physical plan? Call
explain()(orexplain("formatted")), read it from the bottom up, and look forExchange(a shuffle), the join operator chosen, and whetherPushedFilterslists your filter on the file scan. - Why do Parquet and ORC matter for Spark? They are columnar, compressed and store min and max statistics, so Spark reads only the columns you select and can skip row groups that cannot match a filter.
from pyspark.sql import SparkSession, functions as F
spark = (
SparkSession.builder.appName("daily-revenue")
# replace only the dates this run writes; the default static mode would
# wipe every older partition under the output path
.config("spark.sql.sources.partitionOverwriteMode", "dynamic")
.getOrCreate()
)
orders = spark.read.parquet("s3://lake/orders/") # partitioned by order_date
daily = (
orders
.filter(F.col("order_date") >= "2026-11-01") # partition pruning + pushdown
.filter(F.col("status") == "paid")
.groupBy("order_date", "country") # wide: one shuffle here
.agg(F.sum("amount").alias("revenue"),
F.countDistinct("customer_id").alias("buyers"))
)
daily.explain("formatted") # look for Exchange and PushedFilters
daily.write.mode("overwrite").partitionBy("order_date").parquet("s3://mart/daily_revenue/")Partitioning, shuffles and data skew
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What decides how many partitions a DataFrame has? | Parallelism | For file reads, the file sizes and the max partition bytes setting. After a shuffle, spark.sql.shuffle.partitions, which defaults to 200, unless adaptive query execution coalesces them. |
| repartition versus coalesce? | Cost awareness | repartition does a full shuffle and can raise or lower the count, giving evenly sized partitions. coalesce only merges existing partitions without a shuffle, so it is cheap but can leave uneven sizes. |
| What is partitionBy on write, and what can go wrong? | Layout | It writes one folder per value of the chosen columns so later reads can prune. Picking a high-cardinality column creates millions of tiny files and slow listings. |
| What is data skew and how do you spot it? | Diagnosis | A few keys hold most of the rows, so a handful of tasks process far more data. In the Spark UI the stage's max task time and shuffle read size dwarf the median. |
| How do you fix a skewed join? | Remedies | Broadcast the small side if it fits; let adaptive query execution split skewed partitions; filter or handle null and default keys separately; or salt the hot keys so their rows spread over several partitions. |
| groupByKey versus reduceByKey? | RDD-era classic | reduceByKey combines values on each partition before the shuffle, so far less data moves. groupByKey ships every value and can run executors out of memory on a hot key. |
| What causes the small files problem and how do you fix it? | Storage hygiene | Many tasks each writing a small file, often after a wide shuffle or high-cardinality partitionBy. Compact with a repartition before the write, tune output file size, or use table format compaction. |
| What does adaptive query execution change at runtime? | Modern Spark | Using real shuffle statistics, it coalesces small shuffle partitions, switches a sort-merge join to a broadcast join when one side turns out small, and splits skewed partitions. It is on by default since Spark 3.2. |
import random
from collections import Counter
random.seed(7)
keys = ["user_1"] * 9000 + [f"user_{i}" for i in range(2, 1002)]
def bucket(key, buckets=8):
return hash(key) % buckets
def salted_bucket(key, salts=8, buckets=8):
return (hash(key) + random.randrange(salts)) % buckets
plain = Counter(bucket(k) for k in keys)
salted = Counter(salted_bucket(k) for k in keys)
print("largest bucket, plain: ", max(plain.values())) # about 9,100 rows in one bucket
print("largest bucket, salted:", max(salted.values())) # about 1,300 rows in the largest bucketJoins, caching and memory
- Which join strategies can Spark pick? Broadcast hash join (small side copied to every executor, no shuffle of the big side), sort-merge join (both sides shuffled and sorted by key, the default for two large tables), shuffle hash join, and nested loop joins for non-equi conditions.
- When does Spark broadcast automatically? When its size estimate for one side is under
spark.sql.autoBroadcastJoinThreshold(10 MB by default). You can force it withF.broadcast(df), but a wrong guess can exhaust driver or executor memory. - cache versus persist?
cache()ispersist()with the default storage level, which for DataFrames keeps data in memory and spills to disk. Caching is lazy: nothing is stored until an action runs. Unpersist when the reuse ends. - When is caching a mistake? When the DataFrame is used once, when it is larger than executor memory and keeps getting evicted, or when the upstream read is cheap columnar storage that would be faster to scan again.
- Why did the driver run out of memory? Usually
collect()ortoPandas()on a large result, a huge broadcast, or too many partitions and tasks for the driver to track. The fix is to keep the data distributed and write results out instead. - What is executor memory overhead? Memory outside the JVM heap for native buffers, Python workers and the like. Containers killed by YARN or Kubernetes for exceeding limits often need more overhead, not more heap.
- What is a checkpoint, and how is it different from cache? A checkpoint writes the data to reliable storage and cuts the lineage, which helps with very long iterative plans. A cache keeps lineage and can be lost with an executor.
Structured Streaming
| Question | What it tests | What a strong answer shows |
|---|---|---|
| How does Structured Streaming model a stream? | Concept | As an unbounded table that grows. You write the same DataFrame query as for batch, and Spark runs it incrementally, by default in micro-batches. |
| What is the checkpoint location for? | Recovery | It stores source offsets and state so a restarted query continues where it stopped. Changing the query shape can make an old checkpoint unusable. |
| What does a watermark do? | Late data | It tells Spark how late events may arrive for event-time windows. State older than the watermark is dropped, which bounds memory, and rows later than that are ignored. |
| Append, update and complete output modes? | Semantics | Append writes only rows that will never change. Update writes rows changed in this trigger. Complete rewrites the whole result each time and only suits small aggregations. |
| How do you get end-to-end exactly-once? | Guarantees | A replayable source such as Kafka, the checkpoint for offsets and state, and a sink that is idempotent or transactional, such as a table format that commits each batch once. |
| Spark Streaming (DStreams) versus Structured Streaming? | History | DStreams is the older RDD-based API and is legacy. Structured Streaming builds on DataFrames and the optimizer and adds event-time processing. |
Hadoop and the wider big data stack
- How does HDFS store a file? It splits it into large blocks (128 MB by default in current Hadoop) and stores each block on several DataNodes, three copies by default. The NameNode keeps the metadata: which blocks make up which file and where they live.
- What happens if a DataNode fails? The NameNode notices missing heartbeats and schedules new copies of the under-replicated blocks from the surviving replicas.
- Why is the NameNode a concern? It holds all metadata in memory, so many small files eat its memory, and without high availability it is a single point of failure. HA setups run an active and a standby NameNode.
- What do YARN's ResourceManager, NodeManager and ApplicationMaster do? The ResourceManager allocates cluster resources, each NodeManager runs containers on its machine, and each application gets an ApplicationMaster that requests containers and tracks its tasks. Spark on YARN runs its executors in those containers.
- Walk through a MapReduce job. Mappers read input splits and emit key-value pairs, the framework sorts and shuffles them by key, and reducers aggregate each key's values. A combiner can pre-aggregate on the map side.
- Why is Spark usually faster than MapReduce? MapReduce writes intermediate results to disk between every map and reduce step. Spark plans multi-step pipelines as one DAG, pipelines narrow steps in memory and only writes shuffle files where it must.
- Where do Hive, Delta Lake and Iceberg fit? Hive introduced SQL tables and a metastore over HDFS files. Delta Lake and Apache Iceberg are table formats that add transactions, schema evolution and time travel on top of Parquet in object storage, and Spark reads and writes both.
Senior and scenario questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| A job's last 3 tasks out of 400 run for an hour. | Skew diagnosis | Check the stage's task metrics for shuffle read size by task, find the hot join or group key, then broadcast, salt, or rely on adaptive skew handling. Also check for a flood of null keys. |
| A job that ran in 20 minutes now takes 3 hours with the same code. | Investigation | Compare input volume and file counts, look for new small files, a changed partition layout, a join that lost its broadcast because a table grew, or a cluster with fewer executors. |
| Executors keep getting killed for exceeding memory. | Memory tuning | Separate heap from overhead in the error. Reduce partition size with more shuffle partitions, avoid wide rows from exploded arrays, raise overhead for Python-heavy jobs, and check for a skewed partition. |
| Design a daily pipeline that rebuilds a 5 TB fact table. | Design | Read only new partitions, write partitioned output by date, overwrite partitions dynamically instead of the whole table, use a transactional table format, and make reruns idempotent. |
| How would you size executors for a job? | Resource planning | A few cores per executor (often 4 or 5) to balance parallelism with garbage collection and I/O, memory per core sized to the largest partition you expect, and dynamic allocation for spiky stages. |
| The streaming job's batch duration keeps growing. | Streaming ops | Input rate is above processing rate or state keeps growing. Check the watermark, the state size, trigger interval and sink latency; add parallelism or cap input per trigger. |
Fictional example
- Interviewer
- We join a few billion click events to a users table every night and it has become very slow. Where do you start?
- Candidate
- I would open the Spark UI for the join stage before changing anything. First I want to know the join strategy from the physical plan. If the users table is a few hundred megabytes, a sort-merge join means both sides are being shuffled, and broadcasting users would remove the shuffle of the clicks entirely. Second, I would look at the task durations in that stage. If the median task takes 30 seconds and the max takes 40 minutes, that is skew, probably from anonymous clicks with a null or placeholder user id. I would split those rows out and handle them separately, since they cannot match a user anyway. If real users are hot, salting their keys or relying on adaptive skew join handling spreads them out. Third, I would check the input: are we reading only last night's click partition, and are we selecting only the columns we need? A lot of slow joins are really slow scans.
How to prepare for Spark and Hadoop interview questions
- Run Spark locallyInstall PySpark on your laptop, load a public dataset of a few gigabytes, and open the Spark UI on port 4040 while queries run. Find the stage boundaries for a groupBy and a join.
- Read plans on purposeFor five queries, predict the physical plan, then call explain and compare. Note every Exchange, the join operator and the pushed filters.
- Break thingsCreate a skewed key, collect a big DataFrame to the driver, write with a high-cardinality partitionBy. Seeing each failure once makes the scenario answers concrete.
- Rehearse the Hadoop basicsBe able to draw HDFS (NameNode, DataNodes, blocks, replicas), YARN (ResourceManager, NodeManagers, containers) and one MapReduce flow in two minutes each.
- Connect it to pipelinesKnow how a Spark job is scheduled by an orchestrator such as Airflow, and where its output lands in a warehouse or lakehouse model.
Spark rarely stands alone in a data loop. The Airflow interview questions page covers how jobs like these get scheduled and retried, data warehouse interview questions covers the fact and dimension tables they feed, and the data engineer interview questions page puts both into a full role loop.
Practicing Spark answers out loud shows quickly whether you can explain a shuffle without hand-waving. In a mock round, Natively, an AI interview assistant for Mac and Windows, writes a transcript of what you said, can suggest an answer to set beside your own, and reads a Spark UI stage table, a query plan or a PySpark exercise from a screenshot. With Pro or the free trial it also draws on the résumé and job description you add, and each practice session's transcript and notes stay available to review afterward.
Questions people ask
What are the most common Spark interview questions?
Driver versus executors, jobs, stages and tasks, narrow versus wide transformations, lazy evaluation, RDD versus DataFrame, repartition versus coalesce, data skew, broadcast joins, caching and Structured Streaming.
Are Hadoop interview questions still asked?
Yes, mostly as background. Expect HDFS blocks and replication, the NameNode, YARN's ResourceManager and NodeManagers, and how a MapReduce job maps, shuffles and reduces.
What is a shuffle in Spark?
Moving rows between partitions over the network so that rows with the same key end up together, as a groupBy or join requires. Each shuffle ends one stage and starts the next, and it is usually the most expensive step in a job.
How do I prepare for big data interview questions?
Run PySpark locally on a dataset of a few gigabytes, read the Spark UI and query plans for joins and aggregations, reproduce skew and memory errors on purpose, and practice explaining HDFS and YARN in a few sentences each.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
