PySpark Interview Questions (2026)
PySpark combines the distributed computing muscle of Apache Spark with the flexibility of the Python ecosystem. In interviews, expect deep questions on JVM-Python interprocess communication, PySpark DataFrame vs Pandas DataFrame, Pandas UDFs powered by Apache Arrow, and avoiding serialization bottlenecks.
Tested Core Concepts & Weightage
Distribution within this topicUnlocked FAANG-Calibrated Answer Rubric (Top 3 Tested Questions)
- •Rigorous explanation of data distribution, memory boundaries, and execution bottlenecks
- •Quantified improvements (e.g. 60% shuffle volume reduction, predictable SLA under 10x spikes)
- •Proactive trade-off analysis between latency, storage overhead, and operational complexity
Complete PySpark Question Vault (126 Questions)
Showing 15 of 126What are traits in Scala, and how are they different from classes?
**Traits**: Interface-like constructs that can define abstract and concrete methods/fields. Support multiple inheritance of type. Mixed in via `with`. **Classes**: Define objects with state and behavior. Single inheritance; one superclass. **Key Differences**: Traits enable composition; classes define core logic. Traits can be partially implemented; classes hold primary behavior....
Explain the difference between Azure Data Factory (ADF) and Databricks.
ADF is an orchestration and data-movement service; Databricks is a compute platform for analytics and ML. Why it matters: ADF excels at scheduling, branching, retries, and connectors—it's the 'conductor.' Databricks excels at heavy transforms (Spark), Delta Lake, and ML—it's the 'orchestra.' Scalability: ADF scales by parallelism (activities, self-hosted IR nodes); Databricks scales via cluster sizing and auto-scaling....
When would you architecturally choose Dataset[T] over DataFrame in a Scala Spark pipeline, and what are the scalability and portability trade-offs? Include type-safety benefits vs. operational constraints.
DataFrame is an untyped collection of Row objects with schema at runtime; Dataset[T] is typed with compile-time safety. In Scala, DataFrame = Dataset[Row]. Architectural why: Dataset enables domain modeling (e.g., Dataset[Order])—catch errors at compile time, better IDE support, and Catalyst can optimize typed encoders. Scalability: both use Tungsten and Catalyst; Dataset adds encoder overhead but marginal for most workloads. Portability trade-off: PySpark has only DataFrame—no typed Dataset....
Convert complex SQL (CTEs, window functions, subqueries) to production-grade PySpark. Discuss when to use spark.sql() vs. DataFrame API, and the implications for testability, partitioning, and execution predictability.
Two approaches: spark.sql() for direct translation and DataFrame API for programmatic logic. SQL approach: createOrReplaceTempView, run ANSI-like SQL—fast parity, but string-based, harder to unit test, and execution plan less explicit. DataFrame API: composable, testable (pass mock DataFrames), explicit transformations....
Explain strategies for managing schema changes in PySpark over time.
Schema evolution in PySpark is architecturally driven by two competing forces: storage economics (rewriting entire datasets is costly) and query correctness (downstream consumers break when schemas shift). **Why it matters**: At petabyte scale, a full rewrite for a new column can cost thousands in compute and hours of downtime. **Strategies with trade-offs**: (1) mergeSchema—additive only, zero rewrite cost, but schema drift accumulates; use for append-heavy pipelines....
How do you drop columns with null values in PySpark?
Two distinct operations: (1) **Drop columns that are entirely null** (no non-null values): null_cols = [c for c in df.columns if df.filter(col(c).isNotNull()).count() == 0]; df = df.drop(*null_cols). **Caveat**: count() triggers a full scan—expensive on large tables. (2) **Drop rows with null in specified columns**: df.dropna(subset=["col1", "col2"]). **Scalability**: The column-null check is O(partitions × columns) and can be costly; consider sampling or inferring from schema/sample....
How do you optimize Spark jobs for performance?
Optimization is a hierarchy: (1) **Reduce data scanned**—partition pruning, predicate pushdown, column pruning; biggest lever. (2) **Reduce shuffle**—broadcast small tables, avoid unnecessary repartitions, co-locate joins. (3) **Right-size parallelism**—spark.sql.shuffle.partitions ~2–4× cores; too many = task overhead; too few = underutilization. (4) **Avoid serialization hot paths**—use built-in functions over UDFs; UDFs break Catalyst and force row-by-row Python or slower Java....
How would you read data from a web API using PySpark?
PySpark has no native API source; the pattern is driver fetch or executor fetch. **Approaches**: (1) **Driver + parallelize**: data = requests.get(url).json(); df = spark.createDataFrame(data). Scales to API response size (typically MBs); driver is bottleneck. (2) **mapPartitions on executor**: Pass partition of IDs to each task; each calls API. Scales to many IDs but risks rate limiting and API abuse. (3) **Orchestrator + landing**: Airflow/Prefect fetches API → lands to S3/GCS → Spark reads....
What is the difference between Spark RDDs, DataFrames, and Datasets?
**RDD**: Low-level, immutable, partitioned collection of objects; no schema; no Catalyst; Python UDF forces serialization row-by-row. **DataFrame**: Rows with named columns; Catalyst + Tungsten; untyped (Row). **Dataset (Scala/Java)**: Typed DataFrame; compile-time type safety; same optimization as DataFrame. **Architectural trade-off**: RDD gives full control (custom partitioner, arbitrary types) but no optimizer help; DataFrame/Dataset trade control for 5–10x speedup on analytical workloads....
Why is SparkSession used in Spark 2.0 and later versions?
**SparkSession** (2.0+) is the unified entry point for DataFrames, Datasets, SQL, and Structured Streaming. It subsumes SparkContext, SQLContext, HiveContext, and StreamingContext. **Why it matters**: Single API for DataFrame/SQL/Streaming reduces boilerplate and simplifies configuration. One session manages config, catalog, and context. **Architectural benefit**: Consistent behavior across Scala, Python, R; easier migration from RDD to DataFrame; Hive support via `.enableHiveSupport()`....
Write a Python script to find the count of each word in a text file using Spark.
To count word occurrences in a text file using Spark, the standard approach leverages the PySpark DataFrame API to read the file, tokenize lines into words, and then aggregate these words. This method…
Write the PySpark code to find the second highest salary in each department.
To find the second highest salary in each department using PySpark, the most robust and idiomatic approach leverages window functions. Specifically, you partition the data by department, order it by…
Introduce yourself, highlighting key projects and tech stacks
Situation: Opening of technical interview. Task: Concise, impact-focused intro. Action: 'I'm a Senior DE with X years—built real-time (Kafka/Flink) and batch (Spark/Delta) pipelines. Key projects: migration that cut costs 40%, platform that reduced failures 80%. Stack: Python, SQL, Spark, Airflow, dbt, AWS....
Tell me about yourself and your professional background.
Situation: Opening question. Task: Concise narrative. Action: 'Senior DE, X years, [companies]. Specialize in [streaming/batch/quality]. Skills: Python, Spark, SQL, cloud. Led migrations, platform tooling, mentored. Motivated by scale and reliability....
Data Factory vs. Databricks: When to use which?
Why differentiate: Wrong tool = slow, expensive, or unmaintainable. ADF: Orchestration, simple copy, low-code, diverse sources, on-prem connectors. Databricks: Massive Spark processing, custom Python/Scala, ML, performance-critical, fine-grained compute control. Architectural logic: ADF = plumbing; Databricks = heavy lifting. Together: ADF orchestrates, triggers Databricks for transforms. Scalability: ADF scales with DIU; Databricks with cluster....
Stop Guessing If Your Answers Clear the Bar at PySpark
DataEngPrep’s AI evaluates your real answers against strict FAANG hire rubrics. Check accuracy, optimize shuffle partitions, detect edge case omissions, and receive an instant 9/10 rewrite before stepping into your real interview loop.
Related Technical Topics & Competencies
Frequently paired together during multi-round senior data engineering loops.
Frequently Asked Questions About PySpark Interviews
Why do custom Python UDFs cause severe performance degradation in PySpark?▼
Standard Python UDFs require PySpark to serialize data from JVM memory, pass it across an IPC socket to a Python daemon process, deserialize it row-by-row, execute the Python function, and serialize the result back to the JVM. This breaks Catalyst optimizations and causes heavy CPU serialization overhead. The fix is using native Spark SQL functions or vectorized Pandas UDFs backed by Apache Arrow.
How does Py4J work in PySpark?▼
Py4J runs on the driver node, allowing Python programs to dynamically access Java objects in a JVM. It converts Python calls into Java calls. However, data processing tasks on worker nodes communicate via Unix sockets or pipes with Python worker processes.
What is the difference between coalesce() and repartition() in PySpark?▼
coalesce() decreases the number of partitions without triggering a full shuffle by merging existing partitions on the same node, making it much faster. repartition() performs a full shuffle across the cluster to redistribute data evenly, and can either increase or decrease the partition count.
Can I run and evaluate PySpark code in real-time on DataEngPrep?▼
Yes! Submit your PySpark scripts to the AI Interview Coach for syntax verification, memory leak analysis, and shuffle minimization recommendations.