Skip to main content
InterviewHubPRO
HomeTracksSection 44: Apache Spark Big Data (50 Qs)
Section 44 of 6450 Questions (1 Per Page)

Apache Spark & Large-Scale Distributed Data Processing Master Interview Bank

Spark driver and executor topology, RDDs vs DataFrames, Catalyst query optimizer, Tungsten execution engine, shuffle partitions, and Delta Lake.

Curriculum Roadmap & Learning Path

3 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.3 Connected Milestones
50 of 50 Qs

Part 1: Basic & Foundational Concepts (Junior / Entry-Level)

10 Questions
1
Senior#apache-spark#Basic

What is Apache Spark and why is it faster than Hadoop MapReduce?

Apache Spark is an open-source, distributed general-purpose cluster-computing engine: MapReduce Bottleneck: Persisted all intermediate data between processing phases to physical disk (HDFS), incurring massive disk I/O and.

2
SeniorCode#Components#System Design

What are the core components of the Apache Spark Architecture (Driver, Cluster Manager, Executors)?

Driver: The central process executing the main function of your program • Cluster Manager: Allocates physical hardware resources across nodes (e.g. Kubernetes, Apache YARN, Mesos, or Spark Standalone) • Executors: Worker processes running on cluster nodes.

3
Senior#System Design

What is an RDD (Resilient Distributed Dataset) and its 3 core characteristics?

An RDD is Spark's fundamental low-level data abstraction: Resilient: Fault-tolerant through lineage graphs • Distributed: Data is partitioned across multiple cluster nodes for parallel processing • Dataset: Represents an immutable collection of typed Java/Scala/Python objects.

4
JuniorCode#apache-spark#Basic

What is the difference between RDD, DataFrame, and Dataset?

RDD: Low-level, unstructured objects, type-safe in Scala/Java, but lacks automatic query optimization • DataFrame: Distributed collection of data organized into named columns (like a SQL table or Pandas dataframe).

5
Junior#apache-spark#Basic

What is Lazy Evaluation in Apache Spark?

Spark does not execute transformations immediately when they are called: Instead, it builds an execution plan recorded in a DAG (Directed Acyclic Graph) • Execution only begins when an Action (e.g. count(), collect(), write) is called.

6
Junior#State Management#Forms

What is the difference between Transformations and Actions?

Transformations: Lazy operations that produce a new DataFrame/RDD from an existing one: map(), filter(), select(), groupBy(), join() • Actions: Eager operations that trigger computation across the cluster and return a value to the Driver or write data to external storage.

7
JuniorCode#Forms

What is the difference between Narrow Transformations and Wide Transformations?

Narrow Transformation: Each input partition contributes to only one output partition • Wide Transformation: Data from multiple partitions must be grouped and exchanged across cluster nodes (Shuffle).

8
Junior#apache-spark#Basic

What is the execution hierarchy: Application -> Job -> Stage -> Task?

Application: The entire Spark program submitted to the cluster • Job: Created every time an Action is invoked in the application • Stage: A Job is split into multiple Stages separated by Shuffle boundaries (wide transformations) • Task: The smallest unit of execution.

9
JuniorCode#apache-spark#Basic

How do you write a basic PySpark DataFrame application?

A standard PySpark application initializes a SparkSession, ingests structured data from distributed storage (such as S3, GCS, or HDFS), chains lazy transformations (filtering, grouping, and aggregations), and writes the computed output back to disk via an action.

10
Junior#apache-spark#Basic

Why should you avoid using `collect()` on large DataFrames?

collect() pulls the entire distributed dataset from all Executors into the Driver node's single memory space: If the DataFrame is 500 GB and the Driver has 8 GB of RAM, the Driver will instantly crash with a fatal java.lang.OutOfMemoryError: Java heap space.

Part 2: Core Architecture & Implementation (Mid-Level)

10 Questions
11
Senior#System Design#Databases & SQL

How does the Catalyst Optimizer optimize Spark SQL queries?

Catalyst is Spark's rule-based and cost-based query optimization engine. It operates in 4 phases: Analysis: Resolves table and column names against the Catalog to produce an Analyzed Logical Plan • Logical Optimization: Applies rule-based optimizations: Predicate Pushdown (filters pushed to storage source) and Column Pruning (reading only.

12
Senior#System Design

What is the Tungsten Execution Engine and how does it manage memory?

Tungsten optimizes Spark's CPU and memory efficiency down to bare metal: Off-Heap Memory Management: Bypasses the JVM garbage collector by storing binary data off-heap using Java's sun.misc.Unsafe • Cache-Aware Computation: Designs algorithms to fit into L1/L2/L3 CPU caches.

13
Senior#System Design

How does the Spark Shuffle mechanism work internally?

A shuffle redistributes data across cluster partitions when grouping or joining: Shuffle Write (Map Side): Each task partitions its output into buckets and writes sorted blocks to local disk on the Executor • Shuffle Spill: If the memory buffer fills up, intermediate sorted partitions spill to local disk.

14
SeniorCode#System Design

What is the difference between `repartition()` and `coalesce()`?

repartition(N): Reshuffles data evenly across N partitions using full network shuffle • coalesce(N): Decreases the number of partitions without a full shuffle by merging adjacent partitions on the same worker node.

15
Senior#System Design

What are the memory regions in Spark's Unified Memory Manager?

An Executor's memory is divided into: Reserved Memory (300 MB): Hardcoded for Spark internal system processes • User Memory (25% of remaining): Stores user data structures, UDF variables, and metadata • Spark Memory (75% of remaining) • Execution Memory: Used for shuffles, joins, sorts, and aggregations.

16
Most AskedSenior#System Design

What is the difference between `cache()` and `persist()`?

cache(): Shortcut for persist(StorageLevel.MEMORYANDDISK) (in DataFrames) or MEMORYONLY (in RDDs) • persist(level): Allows explicitly specifying the storage level • MEMORYONLY: Deserialized in RAM (fastest, high RAM usage) • MEMORYONLYSER: Serialized in RAM (saves 60% memory, slight CPU deserialize cost).

17
SeniorCode#System Design

What are Broadcast Variables and Accumulators?

Broadcast Variable: Sends a read-only lookup table or dictionary to every Executor node once, instead of sending a copy with every single task • Accumulator: Write-only shared variable updated across tasks via associative addition (e.g. counting corrupted rows or tracking metrics across a.

18
Senior#System Design

What are Spark's Join Strategies (Broadcast Hash Join vs Sort-Merge Join vs Shuffle Hash Join)?

Broadcast Hash Join (BHJ): If one table is small (< 10 MB default, configurable via spark.sql.autoBroadcastJoinThreshold), Spark broadcasts the • Sort-Merge Join (SMJ - Default for large tables): Shuffles both tables on the join key, sorts each partition, and merges matching keys sequentially.

19
Senior#System Design

What is Data Skew in Apache Spark and how do you resolve it?

Data skew occurs when one partition contains disproportionately more records than others (e.g. 90% of orders belong to country = 'US'): Symptom: One task in a stage runs for 45 minutes while all other 199 tasks finish in 10 seconds! • Solutions.

20
Senior#System Design

What is Adaptive Query Execution (AQE) in Spark 3.x?

AQE dynamically re-optimizes query plans at runtime based on actual stage execution statistics: Dynamically Coalescing Shuffle Partitions: Automatically combines hundreds of tiny shuffle partitions into optimal partition sizes.

Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)

30 Questions
21
Senior#apache-spark#Advanced Internals

How does Spark Structured Streaming work (Micro-batch vs Continuous)?

Structured Streaming unifies batch and streaming APIs on top of the Catalyst engine: Micro-Batch Engine (Default): Ingests streaming events, processes them as mini-batches (e.g. every 100ms or 1 second) with end-to-end.

22
Senior#apache-spark#Advanced Internals

What are Watermarks in Spark Structured Streaming?

A Watermark defines how long Spark waits for late-arriving streaming events before discarding them from state memory.withWatermark("timestamp", "10 minutes") instructs Spark that events arriving more than 10 minutes past the current event-time threshold can be.

23
Most AskedSeniorCode#State Management#Databases & SQL

What is Delta Lake and how does it provide ACID transactions on Parquet files?

Delta Lake is an open storage layer that brings ACID transactions and reliability to data lakes: Architecture: Stores raw columnar data in Apache Parquet files paired with a forward-only JSON transaction log (deltalog/) • ACID Guarantees: Any write creates a new versioned commit file (000001.json).

24
Senior#PostgreSQL

What are Delta Lake Time Travel, Vacuum, and Optimize (Z-Ordering)?

Time Travel: Query previous table versions: spark.read.format("delta").option("versionAsOf", 5).load(path) • OPTIMIZE + Z-Order: Compresses small files into large 1 GB Parquet files and clusters data multidimensionally along Z-order curves for optimal.

25
Senior#apache-spark#Advanced Internals

How do you calculate optimal Spark Executor Sizing for a cluster?

Assume a 6-node worker node cluster with 16 cores and 64 GB RAM per node: Cores per Executor: Set to 5 cores (ideal balance for HDFS/S3 throughput and GC overhead) • Executors per Node: (16 - 1 OS core) / 5 = 3 Executors per node • Reserve 1 Executor for the Driver -> 17 worker Executors • RAM per Executor: (64 - 1 OS RAM) / 3 ≈ 21 GB.

26
Senior#HTTP & REST APIs

What causes the fatal "Shuffle Fetch Failed" exception and how do you resolve it?

Occurs when a reducer executor attempts to fetch shuffle blocks from an upstream mapper executor that has crashed or timed out: Causes • Mapper executor crashed due to an OutOfMemory error (GC pause > 120s) • Node hardware failure or spot instance termination • Excessive network congestion.

27
Senior#Memory Management

What are the best practices for Garbage Collection (GC) tuning in Spark?

Long GC pauses (> 5s) trigger heartbeat timeouts and kill executors: Use G1GC (Garbage-First Garbage Collector): -XX:+UseG1GC -XX:InitiatingHeapOccupancyPercent=35 • Use DataFrames / Datasets instead of RDDs; Tungsten's off-heap binary format generates zero Java garbage collection objects!

28
Senior#apache-spark#Advanced Internals

How does Spark handle Dynamic Resource Allocation?

Allows Spark to scale the number of allocated Executors dynamically based on queue workload: Spawns additional Executors when tasks are backlogged in the task queue for more than spark.dynamicAllocation.schedulerBacklogTimeout (1s).

29
Senior#apache-spark#Advanced Internals

What is Predicate Pushdown and how does it save petabytes of data scan?

Predicate pushdown moves filter conditions (WHERE country = 'US') down to the physical storage connector (Parquet, ORC, JDBC, Snowflake): The Parquet reader inspects column metadata statistics in file footers without decompressing or parsing rows.

30
Most AskedSeniorCode#Algorithms

How do you implement custom User-Defined Functions (UDFs) vs Pandas Vectorized UDFs in PySpark?

Standard Python UDF: Extremely slow! • Pandas Vectorized UDF (PyArrow): Transmits chunks of columnar data in Apache Arrow format directly into vectorized Pandas / NumPy arrays.

31
Most AskedSenior#System Design

What is the difference between Checkpointing and Caching in Spark?

cache(): Keeps DataFrame partitions in memory or local disk • checkpoint(): Truncates the lineage graph completely and saves physical data to durable distributed storage (HDFS/S3).

32
Senior#Forms#Performance

How do you debug Spark performance bottlenecks using the Spark Web UI?

Stages Tab: Look for stages with high duration • Executors Tab: Inspect GC time (should be < 10% of task time) and shuffle read/write volumes • Storage Tab: Check what percentage of cached DataFrames are resident in memory vs spilled to disk • SQL Tab: Inspect physical execution plans and DAG visualizations.

33
Senior#apache-spark#Advanced Internals

What is the difference between Apache Iceberg and Delta Lake?

Both provide ACID table formats on cloud object storage: Delta Lake: Deeply optimized for Apache Spark and Databricks ecosystems, uses JSON transaction logs and checkpoint Parquet files • Apache Iceberg: Engine-agnostic from day one (equal first-class citizen support for Trino, Flink, Spark, Snowflake, BigQuery), tracks data files.

34
Senior#apache-spark#Advanced Internals

What is the Spark Driver OOM problem and how do you resolve it?

Driver crashes occur when: Calling collect() on massive datasets • Broadcasting a table larger than driver memory (spark.driver.memory) • Excessive broadcast joins exhausting driver heap during serialization • Lineage graph explosion in deep iterative loops (solve with localCheckpoint()).

35
Senior#apache-spark#Advanced Internals

When should you use Apache Flink instead of Apache Spark?

Use Apache Flink: When you require true event-driven, record-by-record processing with ultra-low sub-millisecond latency (fraud detection • Use Apache Spark: When your workload mixes batch data processing, scheduled ELT pipelines, machine learning at scale, interactive SQL analytics.

36
Senior#Performance

Catalyst Optimizer Deep Dive: Analysis, Logical Optimization, Physical Planning, and Cost-Based Optimizer (CBO).

The Catalyst Optimizer is Spark's query compiler that transforms DataFrame code and SQL into highly optimized bytecode: Analysis: Resolves table and column names against the Catalog / Metastore • Logical Optimization: Applies rule-based transformations.

37
Most AskedSenior#Memory Management#System Design

Tungsten Execution Engine: Off-heap memory management, cache-aware computation, and Whole-Stage Code Generation.

Before Tungsten, Spark spent massive CPU cycles on JVM object overhead, GC pauses, and CPU L1/L2 cache misses: Off-Heap Memory Management: Manages raw binary memory using sun.misc.Unsafe, eliminating Java object wrapping overhead and completely bypassing.

38
SeniorCode#apache-spark#Advanced Internals

Dynamic Partition Pruning (DPP): How star-schema joins skip reading hundreds of gigabytes of partition files.

In data warehousing star-schemas (joining a massive partitioned Fact table with a small Dimension table).

39
Senior#apache-spark#Advanced Internals

Adaptive Query Execution (AQE): Dynamic coalescing of shuffle partitions, dynamic switching to broadcast joins, and runtime skew join mitigation.

Before AQE (Spark 3.0+), Spark had to guess execution plans using static estimates: Dynamic Coalescing of Shuffle Partitions: Automatically merges small post-shuffle partitions together, solving the spark.sql.shuffle.partitions.

40
Most AskedSenior#State Management#Memory Management

Memory Management Architecture: Storage Memory vs Execution Memory, memory fractions, and off-heap memory.

Spark divides executor JVM heap into distinct pools: Reserved Memory (300 MB): Reserved for Spark internal engine processes • Spark Memory (spark.memory.fraction = 0.6): The remaining 60% of heap is dynamically shared between • Execution Memory: Used for shuffles, joins, sorts, and aggregations.

41
Most AskedSenior#Lifecycle#Kubernetes

Spark on Kubernetes (K8s): Native Spark operator, executor pod lifecycle, dynamic PVC allocation, and spot instances.

Running Spark natively inside Kubernetes without YARN: Spark K8s Operator: Manages Spark applications declaratively using custom resources (SparkApplication) • Driver Pod: Spun up first; acts as the controller that requests executor pods via the Kubernetes API server.

42
Senior#apache-spark#Advanced Internals

Data Skew Resolution Techniques: Salting partition keys and two-stage aggregations.

When 90% of rows contain userid = 'GUEST', all those rows route to a single partition, leaving 99 executors idle while 1 executor runs for 45 minutes: Key Salting • Append a random integer (0 to 9) to the skewed key: concat(key, "", floor(rand() * 10)) • The skewed data evenly disperses across 10 separate parallel partitions.

43
Senior#apache-spark#Advanced Internals

Spark Streaming Watermarking and Late Data Handling: Sliding vs Tumbling windows, event-time, and output modes.

In streaming pipelines, network delays mean events arrive out of order: Event-Time: The timestamp embedded inside the record when the action occurred • Watermark (withWatermark("timestamp", "10 minutes")): Tells Spark how late data can arrive before being discarded • Output Modes.

44
SeniorCode#apache-spark#Advanced Internals

File Compaction Strategies: Small file problem mitigation in Delta Lake/Iceberg.

Streaming or hourly ingestion creates millions of tiny 1MB files. Query engines spend 90% of their time on object storage HTTP listing and opening file headers: The Solution: Periodic file compaction.

45
Senior#Forms

Parquet Format Deep Dive: Row Groups, Column Chunks, Dremel encoding, and predicate pushdown.

Apache Parquet is an open-source columnar storage format designed for analytics: Row Groups: Logical horizontal partitions of data (typically 128MB to 512MB) • Column Chunks: Within a row group, all values for a single column are stored contiguously on disk.

46
Senior#apache-spark#Advanced Internals

Spark Executor Sizing Rules of Thumb: Cores, Memory, and Overhead.

Production best-practice executor sizing formulas: Cores per Executor: Keep between 4 and 5 cores (spark.executor.cores = 5) • 5 cores leads to JVM Garbage Collection thrashing • 1 core per executor wastes shared broadcast memory • Executor Overhead Memory (spark.executor.memoryOverhead).

47
Senior#apache-spark#Advanced Internals

Z-Ordering and Multi-Dimensional Clustering in Delta Lake.

Standard database partitioning works well on 1 column (e.g. date), but fails if queries filter on multiple dimensions (date AND customer_id AND region): Z-Ordering: Maps multi-dimensional data onto a 1-dimensional space-filling curve (Morton Curve) while preserving spatial locality.

48
Senior#apache-spark#Advanced Internals

PySpark Serialization Bottlenecks: Py4J socket IPC, CloudPickle overhead, and Arrow-optimized data transfers.

Why native PySpark was historically slower than Scala: Py4J Socket Bottleneck: PySpark driver communicates with the JVM driver over local TCP sockets • Apache Arrow Solution: Arrow provides a standardized columnar in-memory format.

49
Senior#Security & Auth

Spark Security: Kerberos authentication, TLS wire encryption, and fine-grained data masking via Apache Ranger.

Securing enterprise big data infrastructure: Kerberos: Mutual authentication between Spark drivers, executors, HDFS, and Hive Metastore • Internal Wire Encryption (spark.authenticate = true, spark.network.crypto.enabled = true): Encrypts shuffle data transferred across nodes using.

50
Senior#Memory Management#Docker & Containers

Debugging Executor OOM: `Java heap space` vs `Container killed by YARN/K8s for exceeding memory limits`.

Distinguishing the two distinct out-of-memory errors: java.lang.OutOfMemoryError: Java heap space • Occurs inside the JVM • Root Cause: Excessive memory allocations during large joins, aggregations, or huge arrays cached in memory.