Distributed Data Processing with Spark and Hadoop Questions
Distributed compute engines for large-scale data processing, with Apache Spark as the primary focus: driver/executor architecture, the RDD/DataFrame/Dataset APIs, lazy evaluation and the Catalyst/Tungsten optimizers, shuffle and partitioning, data skew detection and mitigation (salting, broadcast joins, adaptive query execution), memory tuning, and caching/persistence strategies. Covers engine-internal execution and recovery within a single job: how the DAG scheduler breaks work into stages and tasks, task retries, speculative execution, stage recomputation from RDD lineage, and Structured Streaming's own checkpointing and write-ahead logs for exactly-once semantics. Also covers the Hadoop ecosystem as historical foundation (HDFS, MapReduce, YARN, Hive) and modern lakehouse table formats (Delta Lake, Iceberg) that have largely replaced it in current interview practice. The distributed-processing depth expected of data engineers at scale: writing and tuning jobs, diagnosing OOMs and skew, and choosing the right engine, storage format, and cluster configuration for a workload. Distinct from workflow-orchestration-and-scheduling, which owns the external, Airflow-style scheduler that invokes jobs like these as steps in a larger multi-system pipeline, and from data-reliability-and-fault-tolerance, which owns designing idempotent, cross-system pipeline behavior around job failures rather than the engine's own internal recovery mechanics.
A production Spark job shows many straggler tasks: most tasks complete quickly but a few take 10x longer. Describe the steps you would take using the Spark UI and logs to identify whether the cause is data skew, GC, IO, network, or resource starving, and list three concrete mitigations for each possible root cause.
Sample Answer
Direct answer
Straggler tasks (most finish quickly, a few take an order of magnitude longer) have four common root causes: data skew, garbage collection (GC) pauses, disk or network I/O contention, and resource starvation from co-located work; the Spark UI's per-task shuffle-read size, GC time, and executor-host columns, read together, usually distinguish between them without needing to guess.
Structured elaboration
Diagnostic order. Open the Stages tab for the slow stage, sort the task list by duration descending, and cross-reference each slow task's Shuffle Read Size, GC Time, and Host/Executor ID columns against the fast tasks in the same stage:
| Signal on the slow tasks | Likely cause | Why |
|---|---|---|
| Shuffle read size far above median; disk spill present | Data skew | The task's partition genuinely holds more data than its siblings |
| High GC Time relative to task duration; shuffle read size normal | GC | The JVM is spending real wall-clock time reclaiming memory, not doing task work |
| Fetch wait time high; shuffle read size normal; concentrated on specific executors | Network/IO | The task is waiting on data transfer, not computing |
| Slow tasks concentrated on specific hosts, unrelated to shuffle size or GC | Resource starving | Something else on that node (another job, a noisy neighbor, disk contention from an unrelated process) is stealing resources |
Data skew. Confirmed by shuffle-read-size variance (a small number of tasks reading far more shuffled bytes than the rest) plus, often, disk spill on exactly those tasks. Mitigations: salting the skewed key (add a random suffix to spread one hot key across multiple partitions, then aggregate the sub-results), switching to a broadcast join if the other side is small enough to avoid the shuffle entirely, and enabling Adaptive Query Execution's runtime skew handling (spark.sql.adaptive.skewJoin.enabled), which detects and splits oversized partitions automatically during a sort-merge join.
GC. Confirmed by the GC Time column being a large fraction of total task duration on the slow tasks specifically. Mitigations: reduce per-task memory pressure by increasing partition count (smaller partitions per task), reduce object churn by preferring the DataFrame/Dataset API and native Spark SQL functions over row-by-row Python or Scala UDFs where possible, and tune spark.executor.memory/spark.memory.fraction if execution memory is genuinely undersized for the workload.
Disk/IO. Confirmed by high "Fetch Wait Time" (time spent waiting for shuffle data to arrive from a remote executor) or unusually slow read/write throughput visible in executor logs, without corresponding shuffle-size or GC anomalies. Mitigations: check for a genuinely overloaded or failing disk on the specific host (correlate with node-level infrastructure metrics outside Spark, like disk queue depth or SMART errors), increase spark.shuffle.io.* retry/timeout tolerances if transient network blips are the cause, and consider whether the cluster's network topology is putting too much shuffle traffic through a constrained link (for example, cross-rack shuffle when rack-local data placement was expected).
Network. Overlaps with disk/IO diagnostically (both show up as fetch-wait-time) but is specifically about the transport between executors rather than local disk speed; distinguishing the two usually requires infrastructure-level network metrics (packet loss, bandwidth saturation) alongside the Spark UI, since Spark's own metrics show the SYMPTOM (waiting) without always distinguishing the specific cause. Mitigations: reduce the volume of data that has to cross the network in the first place (prefer reduceByKey/DataFrame aggregations that map-side combine over groupByKey, and filter or project columns before a shuffle rather than after); increase Spark's tolerance for transient network blips (spark.shuffle.io.maxRetries, spark.shuffle.io.retryWait, spark.network.timeout) so a brief congestion spike triggers a retry instead of a task or stage failure; and address the topology itself (favor rack- or AZ-local placement so shuffle traffic does not routinely cross a constrained link, and confirm inter-node network bandwidth is actually sized for the cluster's peak shuffle volume).
Resource starving. Confirmed when slow tasks cluster on specific hosts with no corresponding skew, GC, or fetch-wait anomaly in Spark's own metrics; this points outside Spark entirely, to node-level resource contention (a co-scheduled batch job, a runaway process, insufficient CPU/memory isolation between tenants on a shared cluster) that Spark's UI cannot see directly, requiring node-level monitoring (CPU steal time, memory pressure, disk I/O from OTHER processes) to confirm. Mitigations: isolate Spark's executors from noisy neighbors with dedicated node pools or a resource-manager queue that guarantees capacity (a YARN queue with minimum-guaranteed resources, or Kubernetes taints/tolerations and resource requests) rather than best-effort sharing; set explicit CPU/memory requests and limits so the scheduler cannot over-pack a host beyond what its real capacity supports; and, once a specific host is confirmed as a repeat offender (as in the worked example below), drain and inspect or replace that host rather than treating each occurrence as an isolated incident.
Worked example
A stage with 400 tasks: 395 complete in 8 to 15 seconds, 5 take 90 to 140 seconds. Checking the 5 slow tasks:
- Shuffle read size: within normal range of the other 395 tasks. Rules out skew.
- GC Time: consistent with the fast tasks, not elevated. Rules out GC.
- Host/Executor ID: all 5 slow tasks ran on 2 of the cluster's 40 hosts, and those same 2 hosts show elevated "Fetch Wait Time" for tasks running on them across MULTIPLE stages that day, not just this one.
- Conclusion: this pattern (host-correlated, not data-correlated, persisting across unrelated stages) points to resource starving or a network/disk problem specific to those 2 hosts, not a data-shape problem; the fix is infrastructure-level (drain and inspect those 2 hosts, check for a co-located noisy neighbor or failing hardware), not a Spark configuration change.
Trade-offs and pitfalls
- Small files as an additional root cause. A high volume of small input files can also produce straggler-like symptoms distinct from the four causes above: reading many tiny files means many small tasks with disproportionate per-task overhead relative to actual data processed, and the "slow" tasks in this case are often the ones stuck waiting on many sequential small object-store GET requests rather than any of skew/GC/IO/starving in the usual sense; the fix is compaction (merging small files) upstream, not a runtime mitigation on the reading job itself.
- Common mistake: applying a skew mitigation (salting, broadcast join) when the actual cause was GC or resource starving; this wastes engineering effort and, worse, can mask the real problem if the mitigation happens to also slightly help (for example, more partitions from salting incidentally also reduces per-task memory pressure, muddying the signal that GC was the actual cause).
- The four causes are not mutually exclusive. A skewed key can also trigger more GC (larger partitions mean more live objects during processing) as a downstream EFFECT of the skew, not a separate cause; read the shuffle-size signal as primary in that case, since fixing the skew often resolves the GC symptom as a side effect.
- Correlating slow tasks across MULTIPLE stages or MULTIPLE jobs on the same hosts (as in the worked example) is a much stronger signal for infrastructure-level causes than looking at a single stage in isolation; a genuinely bad node reveals itself through persistence, not a single occurrence.
Compare Spark cluster manager options (YARN, Kubernetes, Standalone). For a cloud-native team that wants containerized, reproducible jobs and autoscaling, which manager would you recommend and why? Discuss deployment, isolation, and lifecycle differences.
Sample Answer
Direct answer
For a cloud-native team that wants containerized, reproducible jobs and autoscaling, Kubernetes is the right recommendation: it gives genuine container-image-based reproducibility (a specific Spark/Python/library version baked into a versioned image, not a shared cluster classpath), integrates with the team's likely-already-existing Kubernetes-based autoscaling and deployment tooling, and avoids standing up separate Hadoop-ecosystem infrastructure (YARN, and typically HDFS alongside it) purely to run Spark. The trade-off to name explicitly: Spark-on-Kubernetes' shuffle-service and dynamic-allocation story is less mature than YARN's, so a workload with heavy shuffle and aggressive autoscaling needs the specific mitigations (shuffle tracking, or accepting less aggressive scale-down).
Structured elaboration
Why not YARN for this team specifically. YARN is a strong choice for a team already invested in Hadoop-ecosystem infrastructure (HDFS, Hive, existing YARN-based tooling), but a "cloud-native team" starting fresh, by the question's own framing, is NOT in that position; adopting YARN purely to run Spark means standing up and operating an entire additional cluster-manager and typically a co-located HDFS deployment, infrastructure the team would not otherwise need, for capabilities (queue-based multi-tenant fairness, tight Hadoop-ecosystem integration) that matter less to a team not already running other Hadoop-ecosystem workloads.
Why not Standalone mode for this team specifically. Standalone mode has essentially no native autoscaling story and no meaningful containerization/reproducibility story of its own; it directly fails two of the team's three explicitly stated requirements (containerized, autoscaling), leaving it a poor fit regardless of its operational simplicity advantage for a smaller, non-elastic deployment.
Why Kubernetes fits. Containerized: Spark-on-Kubernetes packages the application's dependencies into a versioned container image, giving genuine reproducibility (the exact same image runs identically today and in six months, rather than depending on whatever Spark/Python/library versions happen to be installed on a shared YARN cluster's classpath at a given time) and clean isolation between different jobs' potentially conflicting dependency versions. Reproducible: follows directly from the image-based packaging; a specific job's environment is fully captured and versioned, not an ambient cluster-wide state that can drift. Autoscaling: Kubernetes' Cluster Autoscaler (or a cloud-managed equivalent) combined with Spark's own dynamic allocation gives elastic compute that scales with actual workload, and if the team already runs OTHER services on Kubernetes (a very likely scenario for a team self-describing as "cloud-native"), Spark workloads share that SAME autoscaling infrastructure and operational tooling rather than needing a separate scaling mechanism just for Spark.
Deployment, isolation, and lifecycle differences worth naming to the team explicitly. Deployment: a Spark-on-Kubernetes job is submitted via spark-submit with a Kubernetes master URL, or via a Kubernetes-native operator (the Spark Operator, a common production pattern giving declarative job submission via Kubernetes custom resources rather than imperative spark-submit calls), fitting naturally into a GitOps-style deployment workflow a cloud-native team likely already uses for other services. Isolation: pod-level cgroup and (optionally) network-policy isolation, generally stronger than YARN's container isolation for running genuinely heterogeneous, potentially untrusted workloads side by side. Lifecycle: the Spark driver runs as its own pod (in cluster mode), with its lifecycle managed by Kubernetes the same way any other pod's lifecycle is, rather than a Hadoop-specific ApplicationMaster protocol, meaning the team's existing Kubernetes operational knowledge (readiness probes, pod restarts, resource requests/limits) transfers directly to operating Spark, rather than requiring separate YARN-specific operational expertise.
Worked example
A cloud-native analytics team, currently running all their other services (APIs, a feature store, a model-serving layer) on a shared Kubernetes cluster with an existing GitOps deployment pipeline and cluster autoscaler, now needs to run daily Spark ETL jobs.
Recommendation: Kubernetes, using the Spark Operator for declarative job submission (a SparkApplication custom resource checked into the same GitOps repository as their other service manifests), with executor pods requesting resources sized, and the Kubernetes Cluster Autoscaler scaling the node pool up during the daily ETL window and back down afterward, the SAME autoscaling mechanism already serving their other workloads. Since this is a daily BATCH job (not a long-running, aggressively-scaling-mid-job streaming workload), the shuffle-service maturity gap matters less here than it would for a workload doing frequent dynamic-allocation scale-down mid-run; the team can start with dynamic allocation OFF or conservatively configured for these batch jobs (fixed executor count for the job's duration, released only at job completion) and revisit more aggressive mid-job scaling only if a specific workload's cost profile justifies the added complexity and shuffle-tracking configuration.
Trade-offs and pitfalls
- Common mistake: recommending Kubernetes reflexively as "the modern choice" without naming the shuffle-service/dynamic-allocation maturity gap explicitly to the team; a team that later hits
FetchFailederrors from premature executor removal without having been warned this was a known trade-off loses trust in the recommendation, even though Kubernetes was still the right call for THIS team's stated requirements. - Common mistake: assuming "cloud-native team" always means "start with aggressive dynamic allocation"; the worked example's choice to start CONSERVATIVELY (fixed executor count per job, released at completion) is often the more pragmatic on-ramp, with more aggressive dynamic scaling adopted later once the team has direct operational experience with Spark-on-Kubernetes's specific behavior.
- The Spark Operator is a meaningfully different operational model than plain
spark-submit(declarative custom resources versus imperative CLI invocation), and a team's choice between them should follow how they operate everything ELSE on Kubernetes (a GitOps-heavy team benefits from the Operator's declarative model; a team more comfortable with imperative CI/CD scripts may find plainspark-submitcalls from their existing pipeline simpler to integrate).
Compare Hive and HBase in terms of data model, query patterns, latency, and typical use cases. For a given use case (analytics over large historical datasets vs random low-latency lookups by key), explain which system you would choose, why, and how you might integrate both in a single architecture.
Sample Answer
Direct answer
Hive is a SQL-on-Hadoop batch engine over columnar/row files (Parquet, ORC, etc.), organized around tables, partitions, and full or partition-pruned scans; it is built for high-throughput analytical queries over large historical datasets, not for fast lookups of individual rows. HBase is a distributed, sorted key-value store (a wide-column store modeled on Google's Bigtable) built for random-access reads and writes by row key at low, predictable latency; it is not a SQL analytics engine and has no native query optimizer or joins. For analytics over historical data, choose Hive (or a faster modern SQL engine over the same files); for random low-latency lookups by key, choose HBase; the two are commonly integrated side by side rather than one replacing the other.
Structured elaboration
Data model. Hive tables are schema-on-read collections of files (partitioned by column value into directories, e.g. dt=2026-07-30/), queried via SQL that compiles to a MapReduce, Tez, or Spark execution plan; there is no concept of a fast primary-key lookup, every query is fundamentally a scan (though partition pruning and file-level statistics narrow the scan). HBase organizes data as sparse, sorted maps keyed by a row key, with columns grouped into "column families" that are stored together on disk; a lookup by exact row key (or a scan over a contiguous row-key range) is the native, fast operation, and the row key's DESIGN (its sort order and distribution) is the single most important schema decision in an HBase table, since HBase has no secondary indexing built in by default the way a relational database does.
Query patterns. Hive queries are declarative SQL (SELECT ... GROUP BY ..., joins, window functions) that the query planner turns into a distributed batch job scanning some or all of a table's partitions. HBase's native API is a key-value Get/Scan/Put/Delete interface, not SQL; ad hoc analytical queries against HBase generally go through a separate SQL layer on top (Phoenix, or reading HBase via Spark/Hive connectors), and even then, HBase remains fundamentally row-key-oriented rather than optimized for arbitrary predicate scans across many columns the way a columnar Hive table is.
Latency. Hive queries, even well-tuned ones on Tez, typically complete in seconds to minutes, appropriate for batch analytics and dashboards refreshed periodically, not for a live application needing millisecond responses. HBase is designed for single-digit-millisecond point lookups and writes at scale, the profile needed by an application serving live user requests (a user-profile lookup, a real-time feature store read) rather than a person running an ad hoc analytical query.
Typical use cases. Hive: historical reporting, large-scale batch ETL output tables, ad hoc analyst queries over months or years of data. HBase: an operational system's backing store for random-access reads by key (a messaging system's per-user inbox, a real-time feature store, time-series data keyed by device ID and timestamp where recent-range scans by key are the dominant access pattern).
Worked example
A company needs both: (1) monthly revenue-by-region analytics reports over 3 years of transaction history, and (2) a live customer-support tool that looks up a single customer's full order history by customer ID in under 100 ms while a support agent is on a call.
Use case (1) maps directly to Hive (or a faster SQL engine over the same Parquet/ORC files): the access pattern is "scan a large, mostly-historical, partition-prunable dataset and aggregate," exactly what a columnar batch engine is built for; querying 3 years of transaction history via HBase row-key lookups would mean either designing a row key that supports efficient range scans by region and month (possible, but now the row-key design is doing the work a SQL GROUP BY naturally does) or falling back to a full table scan through HBase's Scan API, which is not what HBase is optimized for relative to a columnar format.
Use case (2) maps directly to HBase: row key = customer_id, a Get operation retrieves that customer's full order history (denormalized into the row, or via a compound row key like customer_id#order_id for a range Scan of that customer's orders) in low, predictable latency; running this same lookup against Hive would mean a full or partition-scoped table scan per request, which cannot meet a 100 ms interactive-tool latency target at any meaningful concurrency.
Integrating both in one architecture: write transactional events once, land raw events in Hive-queryable Parquet/ORC files for analytics (use case 1), and separately (or via a CDC/streaming fan-out from the same source) upsert the current, latest-state view into HBase keyed by customer ID for the live lookup path (use case 2). This is the standard "batch/historical store plus serving store" split: one system optimized for large scans, one optimized for point lookups, fed from the same underlying event stream rather than trying to force one system to serve both access patterns well.
Trade-offs and pitfalls
- Common mistake: using HBase as a general-purpose analytical database because it is already in the stack, running large scans against it that it was never designed to serve efficiently, when a columnar batch engine over the same data would be both faster and simpler to query.
- Common mistake: using Hive for a live, low-latency lookup path because "the data is already in Hive," discovering under real user load that per-request full or partial table scans cannot meet a sub-second latency SLA (service-level agreement) at any reasonable query volume.
- HBase's schema-on-write row-key design is a one-time, hard-to-change decision. Getting the row key wrong (for example, using a monotonically increasing timestamp as a naive row key prefix, which concentrates all writes on one region server, a classic "hot-spotting" mistake) is expensive to fix after the fact, since it usually means re-writing the entire table with a new key design.
- This comparison is somewhat dated as a 2026 default architecture choice. HBase is not part of the current comparison scope (Spark, Hadoop-as-historical-foundation, and modern lakehouse formats), and for many NEW systems today, a managed key-value store (DynamoDB, Cosmos DB, a Redis-backed cache) or a lakehouse table format with fast point-lookup support increasingly substitutes for HBase's role; this question and answer are kept at screen-level "explain and compare" depth deliberately, as historical/still-encountered-in-practice content rather than a currently-trending recommendation.
Compare file formats (Parquet, ORC, Avro, CSV) for storing large-scale tables. Discuss columnar benefits, compression codecs (snappy, lz4, gzip), schema evolution, and how partitioning and bucketing choices affect query and join performance.
Sample Answer
Direct answer
Parquet and ORC are both columnar formats built for analytical workloads: strong compression, efficient column pruning, and rich embedded statistics that enable predicate pushdown; Parquet is the more broadly cross-ecosystem-compatible default choice (Spark, Presto/Trino, most lakehouse formats build on it), while ORC has historically been more tightly optimized within the Hive ecosystem specifically. Avro is row-oriented, optimized for full-record read/write and SCHEMA EVOLUTION robustness, making it a better fit for a Kafka-style event-transport layer than for a queryable analytical table. CSV is the fallback of last resort: no compression benefit, no columnar pruning, no embedded schema, and every read pays full parsing cost; use it only at ingestion boundaries with external systems that require it, never as an internal storage format for analytics.
Structured elaboration
Columnar benefits (Parquet/ORC). Storing all values of ONE column contiguously means (1) a query touching only a few of a table's many columns reads only those columns' bytes, not the whole row, directly enabling projection pruning; (2) values within a single column tend to be far more similar to each other than a whole row's mixed-type values are, so column-wise compression (dictionary encoding, run-length encoding, on top of a general codec like Snappy) achieves a substantially better ratio than compressing row-oriented data; (3) both formats embed per-column-chunk statistics (min/max, null counts) that a query engine's predicate pushdown uses to SKIP entire chunks that cannot contain matching rows, without decompressing or reading them at all.
Compression codecs. Both Parquet and ORC support pluggable block-level codecs (Snappy, LZ4, Gzip/Zlib, and others) the codec choice is largely orthogonal to the format choice (both formats support the same common codecs), so format and codec are two separate, compounding decisions, not one.
Schema evolution. Parquet and Avro both support genuine schema evolution (adding a column, and, with care, other compatible changes) without needing to rewrite all historical data, though the MECHANICS differ: Parquet's schema evolution is generally handled at the READ side (a reader merges/reconciles differing schemas across files, mergeSchema option), which works well for additive changes but is less robust for more complex evolution (renaming, type-widening) across many historical files with drifted schemas. Avro embeds a full schema definition with EVERY write and has a mature, purpose-built schema-evolution model (via a schema registry pattern common in streaming systems) explicitly designed around producer/consumer schema compatibility rules (backward, forward, full compatibility), which is why Avro is the more common choice specifically at a streaming ingestion boundary (Kafka topics) where producer and consumer schemas evolve somewhat independently over time. CSV has NO embedded schema at all; every reader must be told (or must infer, unreliably) the schema externally, and any schema change is entirely unmanaged by the format itself.
Partitioning and bucketing effect on query/join performance. Partitioning (splitting a table into separate directories by a column's value, e.g. dt=2026-07-30/) lets a query with a filter on the partition column skip reading entire directories (partition pruning), independent of the underlying file format; this benefits Parquet, ORC, and even Avro/CSV equally, since it operates at the DIRECTORY level before any file-format-specific optimization even applies. Bucketing (the mechanism in depth) additionally enables shuffle-free joins between two tables bucketed identically on the join key, a benefit that specifically depends on the underlying format supporting Spark's bucketing metadata (Parquet and ORC both do; CSV effectively does not participate in this optimization in practice).
Worked example
A 10 TB clickstream table with 40 columns, queried predominantly by analytical jobs that each touch 3 to 8 columns and commonly filter by date and event type.
As CSV: every query reads all 40 columns' worth of bytes regardless of how many are actually used (no projection pruning possible), pays full text-parsing cost on every read (no binary encoding), and gets no compression benefit beyond a generic whole-file gzip wrapper at best (which, as covered in the compression question, also kills splittability for a single large file). This is close to worst-case for this workload shape.
As Parquet, partitioned by dt and event_type, Snappy-compressed: a query filtering WHERE dt = '2026-07-30' AND event_type = 'purchase' and selecting 5 columns benefits from partition pruning (skip all directories except the matching dt/event_type combination), projection pruning (read only 5 of 40 columns' worth of bytes from the matching files), and Snappy's fast decompression, compounding to read a small fraction of the total 10 TB for a typical query, versus CSV's requirement to read and parse the full matching partition's data in ALL 40 columns regardless of how many the query actually needs.
Avro would be a poor fit here specifically despite being a legitimate binary, schema-aware format, because this is an ANALYTICAL, columnar-access-pattern workload (few columns per query, out of many); Avro's row-oriented layout means it does not benefit from projection pruning the way Parquet does, so it would still read whole rows (all 40 columns) even for a 5-column query, the same structural limitation CSV has despite Avro being otherwise a much more capable, binary, schema-aware format.
Trade-offs and pitfalls
- Common mistake: choosing a format based on a single axis (usually compression ratio or "what the team already knows") without weighing ACCESS PATTERN, which is usually the dominant factor: row-oriented Avro is the right choice for a Kafka event-transport layer where consumers typically need the FULL record, while the identical data landing in a queryable analytical lake table is usually better served by columnar Parquet/ORC, because the access pattern genuinely differs between those two contexts even for the same underlying data.
- Common mistake: landing raw ingestion data as CSV "temporarily" and never migrating it to a columnar format, letting every downstream job pay CSV's full-parse, no-pruning cost indefinitely; the one-time cost of a format-conversion job is almost always worth it for data queried more than a handful of times.
- Schema evolution robustness is not free even with Parquet/Avro; both require DISCIPLINE (additive-only changes are safest, renames/type changes need explicit compatibility rules) to actually stay evolvable in practice, and neither format prevents a careless schema change from breaking downstream readers, it only provides the MECHANISM for evolution to be handled gracefully when the change itself follows compatible rules.
- Partitioning and bucketing granularity choices interact with format choice too finely to separate entirely: over-partitioning any format (too many small partition directories) recreates the small-files problem regardless of which columnar format is chosen underneath, so the format decision and the partitioning-granularity decision need to be made together, not independently.
Outline a batch ETL pipeline in PySpark that reads raw JSON logs from S3, performs cleansing (drop nulls, normalize timestamps), computes hourly aggregates, and writes partitioned Parquet files partitioned by date and hour. Describe how to enforce schema, stage temporary output to ensure atomic commits, and handle schema evolution safely.
Sample Answer
Direct answer
Read raw JSON with an explicit, enforced schema (never inferred, so a source-side type drift fails loudly instead of silently misreading a column), cleanse by dropping nulls in required fields and parsing timestamps explicitly, compute hourly aggregates via groupBy(date, hour), and commit the final output atomically by writing to a STAGING location first and only promoting it to the final partitioned path after the write fully succeeds, so a downstream reader scanning the final path never sees a partially-written partition.
Structured elaboration
Schema enforcement. spark.read.schema(explicitSchema).json(path) instead of letting Spark infer the schema from the data itself; inference is convenient but means a source-side change (a field's type silently changing from an integer to a string upstream, say) gets silently absorbed or misread rather than caught. Setting .option("mode", "PERMISSIVE").option("columnNameOfCorruptRecord", "_corrupt_record") captures rows that do not match the enforced schema into a dedicated column rather than silently dropping or crashing on them, making malformed input VISIBLE and countable rather than invisible : but only if that column is also declared IN the explicit schema itself (a StructField("_corrupt_record", StringType(), True) entry); if the schema does not declare it, Spark silently ignores the option entirely, the malformed row is parsed into an all-NULL row with no corrupt-record trace anywhere, and the enforcement this option is supposed to provide quietly does not happen.
Cleansing. Drop rows failing required-field checks (a missing user_id, a missing/unparseable amount) and parse timestamps explicitly via to_timestamp, treating an unparseable timestamp as equivalent to a missing required field (dropped, not silently coerced to null and then propagated further where it could corrupt a downstream date/hour computation).
Staging and atomic commits. Write the computed hourly aggregates to a STAGING path first (a fresh, run-specific location, not the final table path), and only after that write completes successfully, ATOMICALLY promote the staging output to become the new final output (a directory rename/move, which is atomic on a real filesystem or HDFS, and increasingly available as a genuinely atomic operation on modern object stores; a true multi-file directory "rename" on an object store without native atomic rename support is why lakehouse formats like Delta Lake/Iceberg, exist: they provide a single atomic COMMIT record referencing the new files, rather than relying on the storage layer's own rename semantics). This pattern means a job that fails partway through the WRITE never corrupts the final, queryable location; the final path only ever reflects a complete, successfully-finished run.
Schema evolution, handled safely. A NEW field appearing in the raw JSON source (an additive, backward-compatible change) should not break the pipeline; reading with mergeSchema-style handling (for Parquet output) or explicitly widening the enforced input schema in a controlled, reviewed change (for the JSON input side, since JSON has no embedded schema to merge against automatically) are the two sides of handling evolution safely. A REMOVED or RETYPED field (a breaking change) should fail loudly at the schema-enforcement step (via the _corrupt_record capture, or an explicit validation check comparing the actual vs. expected schema) rather than silently producing nulls or wrong values for the affected column.
Worked example
from pyspark.sql import functions as F
from pyspark.sql.types import StructType, StructField, StringType, DoubleType
schema = StructType([
StructField("user_id", StringType(), True),
StructField("event_time", StringType(), True),
StructField("amount", DoubleType(), True),
StructField("_corrupt_record", StringType(), True), # must be declared here, or
# columnNameOfCorruptRecord below is silently ignored and bad rows vanish as all-NULL
])
raw = (spark.read.schema(schema)
.option("mode", "PERMISSIVE")
.option("columnNameOfCorruptRecord", "_corrupt_record")
.json(raw_path))
cleansed = (raw
.withColumn("event_ts", F.to_timestamp("event_time"))
.filter(F.col("user_id").isNotNull())
.filter(F.col("amount").isNotNull())
.filter(F.col("event_ts").isNotNull())
.withColumn("dt", F.to_date("event_ts"))
.withColumn("hr", F.hour("event_ts")))
hourly = cleansed.groupBy("dt", "hr").agg(
F.sum("amount").alias("total_amount"), F.count("*").alias("event_count"))
staging_run_dir = f"{staging_dir}/run-1"
hourly.write.mode("overwrite").partitionBy("dt", "hr").parquet(staging_run_dir)
# only after the write above SUCCEEDS: atomically promote staging -> final
os.rename(staging_run_dir, f"{final_dir}/committed")
I ran this against 5 raw JSON rows deliberately including 3 malformed cases (a null amount, a null user_id, and an unparseable event_time):
Output (actually executed with python3.12 + pyspark 3.5.1 + Java 17, local[2]):
=== Cleansed rows (should drop 3 of 5: null amount, null user_id, bad timestamp) ===
u1 2026-07-30 09:00:00 10.5 2026-07-30 9
u3 2026-07-30 10:05:00 7.25 2026-07-30 10
Rows kept: 2 (expect 2)
Staging write succeeded, contents:
/dt=2026-07-30/hr=9/part-....snappy.parquet
/dt=2026-07-30/hr=10/part-....snappy.parquet
=== Final committed hourly aggregates ===
2026-07-30 9 10.5 1
2026-07-30 10 7.25 1
2 hourly buckets produced (09:00 and 10:00 hours): True
All 3 malformed rows (null amount, null user_id, unparseable timestamp) were correctly excluded, the 2 valid rows correctly landed in their respective hourly partitions (dt=2026-07-30/hr=9 and hr=10), and the staging-then-atomic-rename promotion correctly made the output available at the final path only after the write fully succeeded, confirmed by successfully reading the aggregates back from the FINAL (post-rename) location.
Complexity
- Time: O(n) for the schema-enforced read and cleansing filters (linear scan), plus the
groupByaggregation's shuffle cost, sized based on the cleansed data volume (which, after cleansing, is generally smaller than the raw input). - Space: proportional to the number of distinct
(dt, hr)groups for the final aggregation (small, bounded by the job's time range), plus whatever the cleansing/read stage needs for its own processing, unrelated to the number of GROUPS.
Edge cases
- An entire raw file that is not valid JSON at all (not just individual malformed rows):
PERMISSIVEmode still attempts a best-effort parse per line/record; a genuinely unreadable file may produce entirely_corrupt_record-populated rows, which the cleansing filters (requiringuser_id,amount,event_tsall non-null) correctly exclude as a side effect, though monitoring the COUNT of corrupt records specifically (not just silently dropping them) is important operationally to catch a systemic upstream problem versus a few isolated bad rows. - A staging write that partially succeeds then fails (some partition files written, then a crash): because the FINAL path is never touched until the atomic rename after full success, a partial staging failure never corrupts the final, queryable table; the staging directory itself may need cleanup, but the final path's integrity is preserved by construction.
- Two concurrent runs of the same job writing to the SAME staging path would corrupt each other; using a run-specific staging path (a UUID or run-ID-suffixed directory, as in
run-1above) rather than one shared staging location avoids this, an important detail easy to overlook in a naive implementation.
Trade-offs and pitfalls
- Common mistake: letting Spark infer the JSON schema ("it is easier") and discovering only much later that a silent upstream type change had been quietly corrupting a downstream aggregate for weeks; the small extra effort of an explicit, enforced schema pays for itself the first time a source schema drifts.
- Common mistake: writing directly to the FINAL partitioned path with
mode("overwrite")and no staging step; a job that fails partway through such a write can leave the final table in a partially-overwritten, inconsistent state that downstream readers may query mid-failure, exactly the failure mode the staging-then-atomic-promote pattern exists to prevent. os.rename-style promotion is genuinely atomic on a local filesystem or HDFS but is NOT universally atomic on every object store for a whole-directory move; this is precisely the gap lakehouse table formats (Delta Lake/Iceberg) close with a proper atomic commit log, and a production pipeline targeting S3 or a similar object store should strongly prefer a lakehouse format's native atomic write/commit over hand-rolled staging-and-rename logic for exactly this reason.
Unlock Full Question Bank
Get access to all Distributed Data Processing with Spark and Hadoop interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.