๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Spark UI, History Server and Metrics

Apache SparkOperationsโญ Premium
Apache Spark ยท Interview

The one-line mental model

Observability in Spark means knowing, within a minute of an alert, whether a job is slow because of data skew, an undersized shuffle, too few partitions, or a cluster that is simply out of resources, and the UI, event logs and metrics each answer a different part of that question.

You will be able to navigate from a job summary down to the individual task that took ten times longer than its peers, reconstruct a finished run after the driver is gone, export metrics that Prometheus can scrape, and set alert thresholds that fire on real degradation instead of daily variation.

Prerequisites

  • !Spark execution model: jobs, stages, tasks and shuffles
  • !Comfort reading JSON and basic PromQL or SQL

What You'll Learn

  • 1Map UI tabs to the underlying scheduler phases
  • 2Diagnose skew and shuffle pressure from stage metrics
  • 3Enable event logs and use the History Server after a failure
  • 4Define metrics and alerts that separate signal from noise

Enable the evidence before you need it

Debugging a production job is only possible if the evidence was captured while it ran. Two settings do most of that work: event logging, which writes every scheduler event to durable storage, and the UI itself, which serves live detail from the driver.

python
from pyspark.sql import SparkSession

spark = SparkSession.builder \
    .appName("monitoring-example") \
    .config("spark.ui.enabled", "true") \
    .config("spark.ui.port", "4040") \
    .config("spark.eventLog.enabled", "true") \
    .config("spark.eventLog.dir", "hdfs://logs/spark-events") \
    .config("spark.eventLog.logStageExecutorMetrics", "true") \
    .config("spark.history.fs.logDirectory", "hdfs://logs/spark-events") \
    .config("spark.history.fs.cleaner.enabled", "true") \
    .config("spark.history.fs.cleaner.interval", "24h") \
    .config("spark.history.fs.cleaner.maxAge", "7d") \
    .getOrCreate()

Without eventLog.enabled, a driver that dies on a scheduled cluster takes its diagnostic history with it, and the post-mortem becomes guesswork. Event logs are append-only JSON lines describing stage submissions, task metrics, executor come and go events, and SQL executions, and they are large, so enable the cleaner or accept that your log directory will outgrow the cluster. The live UI only shows the most recent applications on a driver, which is why the History Server on port 18080 is not optional in production.

The tabs and the questions they answer

Each tab corresponds to a layer of the scheduler, and reading them in order narrows a vague complaint about slowness into a specific, testable hypothesis.

TabQuestion it answersSignals worth reading first
JobsWhich action triggered work, and how long did it take?Job duration trend, stage count, failures
StagesWhere did the time go inside that job?Shuffle read and write size, GC time, task spread
TasksIs the work evenly distributed?Min, median and max task duration; straggler ratio
StorageWhat is cached, and is it helping?Cached versus unpersisted size, memory fraction
EnvironmentWhich configuration actually applied?Effective configs, deprecated settings, classpath
SQLWhat did Catalyst plan and execute?Whole-stage codegen time, per-node durations

The Tasks tab is where most answers live. A healthy stage shows task durations clustered tightly together; a stage where the slowest task takes twenty times the median tells you one partition holds far more data than the rest, and no amount of cluster scaling will fix that. Sorting by duration and opening the offending task reveals its partition id, input size and shuffle bytes, which is usually enough to confirm skew.

Diagnosing a slow stage from its numbers

A stage record gives you four facts: how much data it read and wrote, how long the median task ran, how far the slowest task deviated, and how much time went to garbage collection. Interpret them together rather than in isolation.

Large shuffle write with a wide task duration spread points to skewed keys, where one hot value forces a single reducer to do everyone else's work. Large shuffle read with even durations points instead to too few partitions, so parallelism rather than data is the constraint. High garbage collection time relative to task duration suggests each executor holds too much per partition, which is a memory sizing or caching problem. Input read is slow but shuffle is small, which usually means the source itself, such as a small-file-heavy S3 prefix, is the bottleneck rather than Spark.

python
from pyspark.sql import functions as F

def diagnose_partitions(df, name="dataset"):
    per_partition = df.withColumn("pid", F.spark_partition_id()) \
        .groupBy("pid") \
        .agg(F.count("*").alias("rows"), F.sum(F.length(F.col("value"))).alias("bytes"))

    stats = per_partition.agg(
        F.count("*").alias("partitions"),
        F.min("rows").alias("min_rows"),
        F.avg("rows").alias("avg_rows"),
        F.max("rows").alias("max_rows"),
    ).collect()[0]

    ratio = stats["max_rows"] / max(stats["avg_rows"], 1)
    print(
        f"{name}: {stats['partitions']} partitions, "
        f"rows min/avg/max = {stats['min_rows']}/{stats['avg_rows']}/{stats['max_rows']}, "
        f"max/avg ratio = {ratio:.2f}"
    )
    if ratio > 5:
        print("  -> likely skew: consider salting the key or enabling AQE skew join")
    return per_partition

A max-to-average ratio above roughly five is the practical skew threshold, and it is worth logging on every pipeline so you see a ratio climbing across releases instead of discovering it during an incident.

The History Server and programmatic listeners

The History Server replays event logs so you can inspect a job that finished yesterday with full UI fidelity, and it is the right tool for trend questions such as whether a stage has been getting slower since a data volume change. Deploy it as a long-running service pointed at the shared log directory, restrict it to your network, and give it enough memory to index logs.

For automated analysis, raw event logs are plain structured data, which makes them queryable without the UI at all.

python
def summarise_event_log(spark, log_path):
    events = spark.read.json(log_path)

    stage_ends = events.filter(F.col("Event") == "SparkListenerStageCompleted")
    stages = stage_ends.select(
        F.col("Stage Info.Stage ID").alias("stage_id"),
        F.col("Stage Info.Stage Name").alias("name"),
        F.col("Stage Info.Task Metrics.Shuffle Write Metrics.Shuffle Write Bytes").alias("shuffle_write"),
        F.col("Stage Info.Task Metrics.Shuffle Read Metrics.Total Bytes Read").alias("shuffle_read"),
    )

    task_ends = events.filter(F.col("Event") == "SparkListenerTaskEnd")
    tasks = task_ends.select(
        F.col("Stage ID").alias("stage_id"),
        F.col("Task Metrics.Executor Run Time").alias("run_time"),
        F.col("Task Metrics.GC Time").alias("gc_time"),
    )

    slowest = tasks.groupBy("stage_id").agg(
        F.avg("run_time").alias("avg_ms"),
        F.max("run_time").alias("max_ms"),
        F.avg("gc_time").alias("avg_gc_ms"),
    ).withColumn("max_avg_ratio", F.col("max_ms") / F.col("avg_ms"))

    return stages, slowest.orderBy(F.col("max_avg_ratio").desc())

Alternatively, attach a SparkListener to the running context to receive job and stage completion callbacks as they happen, which is how custom counters and per-job timings reach your own telemetry without polling the UI.

Metrics worth putting on a dashboard

Spark exports a rich metric set through the Dropwizard registry, and the useful discipline is to pick a small number that describe user experience rather than everything the engine exposes.

MetricWhy it mattersHealthy signal
Batch duration versus trigger intervalDirect measure of whether you are keeping upBelow the interval with headroom
Input lag or records pendingDetects backlog before latency is visibleFlat or declining under steady load
Shuffle bytes writtenCost proxy; growth often means a plan regressionStable for stable volumes
Executor JVM heap and GC timeEarly warning of memory pressureGC under a few percent of runtime
Failed tasks and stage retriesCorrectness and cluster healthZero under normal operation
Under-replicated partitionsReplication is a durability riskZero except during broker loss

Publish them through a Prometheus-compatible sink or a push gateway, then graph batch duration, lag and shuffle volume on the same panel, because the useful signal is usually their relationship: lag rising while batch duration holds steady means input grew, while batch duration rising with flat lag means the query got slower.

Alert thresholds that survive a week on call

Alerting that fires on daily seasonality teaches people to ignore it. Three rules keep alerts meaningful. Alert on sustained conditions rather than instantaneous values, so a five-minute breach of a threshold matters and a thirty-second blip does not. Alert on the derivative where you can, because consumer lag doubling in an hour is a problem even if the absolute number still looks acceptable. And attach a runbook link to every alert, so the responder lands on known diagnostics instead of reconstructing them under pressure.

A practical starting set is: batch duration above the trigger interval for three consecutive batches, consumer lag growing for fifteen minutes, any executor lost more than twice in an hour, and under-replicated partitions above zero for more than five minutes. Everything else belongs on a dashboard reviewed weekly, not in a paging channel. Review the list after every incident: an alert that never fired usefully in six months is either measuring something unimportant or is set so loose it cannot fire, and both cases deserve removal.

Common Mistakes

Running without event logging and relying on the live driver UI

Fix: Enable event logs to durable storage and deploy a History Server so finished jobs stay inspectable

Scaling the cluster to fix a stage with a twenty-times task outlier

Fix: Check the task duration spread first; skew needs salting or AQE, not more executors

Alerting on a single instantaneous metric breach

Fix: Require sustained breach over several evaluation windows before paging anyone

Tracking dozens of metrics nobody acts on

Fix: Publish a small set tied to user-visible outcomes and delete the rest

Best Practices

  • Log max-to-average partition ratios as part of every pipeline run
  • Keep event log retention and cleanup configured so storage use is predictable
  • Put batch duration, lag and shuffle volume on one dashboard to read relationships
  • Attach SparkListener callbacks for custom timings instead of scraping the UI
  • Include a runbook link and a first diagnostic step in every alert definition

Interview Questions

Q1: How do you distinguish data skew from an undersized cluster?

Skew shows as one task or partition far larger than its peers in the Tasks tab with a high max-to-average ratio, while an undersized cluster shows uniformly long tasks and queueing across all of them.

Q2: What does the History Server need that the live UI does not?

Event logs in a shared directory and a long-running service to replay them; the live UI only reflects the current driver and loses everything on restart.

Q3: Which metrics would you alert on for a streaming job?

Sustained batch duration above the trigger interval, growing input lag, executor losses, and under-replicated partitions, each evaluated over a window rather than a single sample.

Q4: Why might GC time be a better alert than heap usage?

Heap percentage varies with caching decisions and is often high by design, whereas GC time rising relative to task duration is direct evidence that allocation pressure is slowing work.

Key Takeaways

  • Enable event logging and a History Server before you need to debug anything
  • The Tasks tab is the fastest path from a slow job to a specific root cause
  • Shuffle size, task spread and GC time together distinguish skew, parallelism and memory problems
  • Dashboard relationships such as lag versus batch duration explain more than isolated metrics
  • Sustained, runbook-linked alerts keep an on-call rotation responsive instead of desensitised
๐Ÿ”’

Premium Content

Spark UI, History Server and Metrics

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement