PySpark interview questions and answers for data engineers
PySpark interview questions test whether you can write Spark jobs in Python without paying the Python tax: knowing that DataFrame code is planned and run on the JVM, that Python UDFs ship rows out to Python workers, and that collect or toPandas can sink the driver. Expect a transformation to write (deduplication, a window, a join), questions on UDFs and Arrow, and a scenario where a job runs slowly or runs out of memory.
By Evin JohnPublished 6 min read
How PySpark questions differ from Spark questions
Most data engineering loops that mention Spark actually test PySpark, because that is what the team writes. The engine questions, such as stages, shuffles, skew and join strategies, are on Spark and Hadoop interview questions. This page covers what changes when the code is Python: where your function really runs, what crosses between the JVM and Python, and which idioms keep the optimizer in charge. Expect a shared notebook or editor task, usually with a small sample DataFrame you build yourself.
- API fluencySelect, filter, groupBy, joins, window functions and null handling, written without looking anything up.
- The Python boundaryUDF types, Arrow, closures, broadcast variables and why some code is slow for Python-specific reasons.
- A coding taskDeduplicate records, compute a rolling metric, or flatten nested JSON into columns.
- Production questionsPackaging dependencies, testing, configuration and an out-of-memory or slow-job scenario.
PySpark fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is a SparkSession? | Entry point | The single entry point for DataFrames, SQL and configuration. It wraps the SparkContext, and in a notebook it is usually created for you as spark. |
| Transformation versus action? | Lazy evaluation | Transformations such as select, filter and join build a plan. Actions such as count, show, collect and write run it. Nothing touches data until an action. |
| Why prefer DataFrames over RDDs in Python? | Performance | DataFrame operations are optimized and executed on the JVM, so Python only describes the plan. RDD lambdas run in Python workers row by row, with serialization costs both ways. |
| How does Python talk to the JVM? | Architecture | On the driver, PySpark uses Py4J to call the JVM SparkSession. On executors, Python workers are started only when Python code must run on the data, such as a UDF or an RDD function. |
| Why define a schema instead of inferring it? | Reliability | Inference reads data to guess types, can guess wrong (IDs as integers, dates as strings) and costs a pass over files. An explicit StructType is faster and fails loudly on bad data. |
| How do you handle nulls in a filter? | Null semantics | Comparisons with null return null, so the row is dropped. Use isNull, isNotNull, coalesce or the null-safe equality eqNullSafe when nulls must match. |
| repartition versus coalesce? | Partitions | repartition does a full shuffle to any number of partitions, evenly. coalesce only merges partitions to reduce the count without a full shuffle, so it can leave them uneven. |
| cache versus persist? | Reuse | cache uses the default storage level; persist lets you choose one, such as memory and disk. Both are lazy and only help when the same DataFrame is used by more than one action. |
| How do you see what Spark will run? | Plans | Call explain on the DataFrame, optionally in formatted mode, and look for scans, pushed filters, Exchange nodes and the join type. |
DataFrame coding questions
The most common live task is to keep only the latest record per key. A window function with row_number is the expected answer; dropDuplicates alone keeps an arbitrary row.
from pyspark.sql import SparkSession, Window
from pyspark.sql import functions as F
spark = SparkSession.builder.master("local[2]").appName("latest").getOrCreate()
events = spark.createDataFrame(
[("u1", "2026-01-02", "gold"), ("u1", "2026-01-05", "silver"), ("u2", "2026-01-03", "gold")],
["user_id", "updated_at", "tier"],
)
newest_first = Window.partitionBy("user_id").orderBy(F.col("updated_at").desc())
current = (
events.withColumn("rn", F.row_number().over(newest_first))
.filter(F.col("rn") == 1)
.drop("rn")
)
current.show() # u1 silver, u2 gold- row_number, rank or dense_rank? row_number always gives one row per position, so it suits deduplication. rank and dense_rank give ties the same number, so two rows with the same timestamp would both survive.
- How do you compute a seven-day rolling sum? A window partitioned by key and ordered by a timestamp cast to seconds, with rangeBetween over the previous seven days. rowsBetween counts rows, which breaks when days are missing.
- How do you flatten nested JSON? Select struct fields with dot paths, use explode or explode_outer for arrays (outer keeps rows with empty arrays), and alias columns to stable names.
- Why is withColumn in a loop slow? Each call adds a projection to the plan, and hundreds of them make planning slow. Build the list of expressions and use a single select.
- How do you write a conditional column? F.when(...).otherwise(...), not a Python if, because the condition must be a column expression evaluated per row on the JVM.
- How do you join two DataFrames that share column names? Join on a list of column names to keep one copy of the key, or alias each DataFrame and select qualified columns, which avoids ambiguous column errors.
- How do you read only the partitions you need? Point the reader at the root of a partitioned Parquet folder and filter on the partition column. Spark skips the other directories, which explain shows as partition filters.
- How do you avoid thousands of tiny files when writing by date? Repartition on the partition column before write.partitionBy, so each task writes one file per date instead of one per date per task.
UDF, Arrow and Python boundary questions
import pandas as pd
from pyspark.sql import functions as F
from pyspark.sql.functions import pandas_udf, udf
@udf("double") # one row at a time, pickled to a Python worker and back
def gross_row(price):
return None if price is None else price * 1.2
@pandas_udf("double") # whole batches as pandas Series, moved with Arrow
def gross_batch(price: pd.Series) -> pd.Series:
return price * 1.2
# Best: a built-in expression, so the work stays on the JVM and the optimizer sees it.
df = df.withColumn("gross", F.col("price") * 1.2)| Question | What it tests | What a strong answer shows |
|---|---|---|
| Why is a plain Python UDF slow? | Serialization | Every row is serialized from the JVM to a Python worker, processed, and sent back. The optimizer also cannot see inside it, so filters are not pushed through it. |
| What makes a pandas UDF faster? | Vectorization | Arrow moves columns in batches, and the function runs vectorized pandas code on each batch instead of a Python call per row. |
| What does enabling Arrow change for toPandas? | Conversion | The conversion to pandas uses Arrow's columnar format instead of row-by-row pickling, which is much faster. It does not change the fact that all the data lands on the driver. |
| Why does referencing a big Python object inside a UDF hurt? | Closures | The closure is pickled and shipped with tasks. A large lookup table belongs in a broadcast variable, or better, in a DataFrame joined with a broadcast hint. |
| Why can you not use the SparkSession inside a UDF? | Execution model | UDFs run on executors in Python workers, where there is no driver session. Pickling a function that captures the session or context fails. |
| What is an accumulator and what is the catch? | Side channels | A counter tasks add to and only the driver reads. Updates made inside transformations may be counted more than once when tasks retry, so use them for diagnostics, not business totals. |
| mapInPandas or applyInPandas? | Grouped pandas | applyInPandas runs a pandas function per group after groupBy; mapInPandas runs over iterators of batches without grouping. Both need an output schema, and a group must fit in one worker's memory. |
Senior PySpark questions and scenarios
| Scenario | Likely cause | What to say you would check |
|---|---|---|
| The driver runs out of memory at the end of the job. | Data pulled to the driver | A collect or toPandas on a large DataFrame, or a large broadcast built on the driver. Aggregate or write in Spark, and limit or sample anything you bring back. |
| A job with one UDF is ten times slower than the SQL version. | Python boundary | Check the plan for a Python evaluation step, then replace the UDF with built-in functions or a pandas UDF. |
| The job works in a notebook and fails on the cluster with an import error. | Dependencies | Executors lack the package. Ship it with the job (zip or wheel through the submit options, or a packed virtual environment) or bake it into the cluster image. |
| Executors are killed even though the JVM heap looks fine. | Python worker memory | Python workers use memory outside the JVM heap, so pandas UDFs on large groups can exceed the container limit. Check overhead settings and group sizes. |
| Tests for transformations are slow and brittle. | Test design | Keep transformations as pure functions from DataFrame to DataFrame, share one local SparkSession across tests with a fixture, and compare small expected DataFrames. |
| A teammate wants to port pandas code by using the pandas API on Spark. | Migration choice | In recent Spark versions this API lets familiar pandas code run distributed, but some operations are costly or behave differently, such as relying on row order. Profile before relying on it. |
Fictional example
- Interviewer
- A job cleans phone numbers with a Python UDF on 400 million rows and takes two hours. What would you look at?
- Candidate
- I would start with the plan, because a Python UDF shows up as a separate evaluation step and tells me every row goes out to a Python worker and back. Cleaning phone numbers is mostly string work, so I would try to express it with built-ins: regexp_replace to strip non-digits, length checks with when and otherwise, and substring for the country code. That keeps everything on the JVM and lets Spark push filters through it. If one rule really needs a Python library, I would use a pandas UDF so the rows travel in Arrow batches, and apply it only to rows the built-ins could not handle. Then I would compare the stage times in the Spark UI before and after, rather than guessing.
PySpark practice plan
- Day 1: install PySpark locally, build small DataFrames by hand, and practise select, filter, groupBy and joins without autocomplete.
- Day 2: solve three window problems: latest record per key, running total, and seven-day rolling sum with rangeBetween.
- Day 3: write the same column as a Python UDF, a pandas UDF and a built-in, time them on a few million rows, and read each plan.
- Day 4: write pytest tests with a shared local session for two transformations.
- Day 5: explain Py4J, Python workers, Arrow and driver memory aloud, each in a minute.
For the role around these questions, see data engineer interview questions and cloud data engineer interview questions. Teams that test pipelines with keyword-driven suites may also ask Robot Framework interview questions.
PySpark answers go wrong when you name a fix before saying where the time goes. Natively, an AI interview assistant for Mac and Windows, transcribes your mock data engineering round on your computer, so you can check whether you diagnosed before prescribing. It can read a DataFrame task or a physical plan from a screenshot and suggest an approach, and with Pro or the free trial it adapts to the résumé and job description you add. You keep the transcript and notes to study afterwards.
Questions people ask
What PySpark questions are asked in interviews?
Transformations versus actions, DataFrames versus RDDs, window functions such as row_number, null handling, repartition versus coalesce, Python UDFs versus pandas UDFs, Arrow, the risks of collect and toPandas, and packaging dependencies.
Why are Python UDFs slow in PySpark?
Each row is serialized from the JVM to a Python worker and back, and the optimizer cannot see inside the function. Built-in functions avoid that, and pandas UDFs reduce it by moving batches with Arrow.
How do I remove duplicates and keep the latest record in PySpark?
Use a window partitioned by the key and ordered by timestamp descending, add row_number, and keep rows where it equals 1. dropDuplicates alone keeps an arbitrary row.
Is PySpark different from Spark in interviews?
The engine is the same, so shuffles and joins still come up. PySpark interviews add Python-specific topics: Py4J, Python workers, UDF types, Arrow and dependency shipping.
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.
