Spark listener
| Also known as | SparkListener, QueryExecutionListener, StreamingQueryListener |
|---|---|
| Field | Monitoring and extension APIs |
| Key parts | Listener bus with asynchronous event queues, SparkListener callbacks, SQL and streaming listener interfaces, registration by configuration or code |
| Open source implementations | Apache Spark |
| Related | Spark event log, Spark UI, Spark History Server, Spark plugin, MLflow, OpenLineage |
A Spark listener is a class that Apache Spark calls back when something happens inside an application, such as a job starting, a task ending, an executor being added or a SQL query finishing.[1] The core interface is org.apache.spark.scheduler.SparkListener; the SQL module adds QueryExecutionListener for completed queries, and Structured Streaming adds StreamingQueryListener for query progress. Listeners are how Spark builds its own Spark UI and Spark event log, and how external tools such as OpenLineage and MLflow observe Spark applications.
How do Spark listeners work?
The driver posts every scheduler event to a listener bus, which delivers events to listeners on background threads, so that a slow listener does not block the scheduler. In Spark 4.3.0 the bus has separate queues: shared for user listeners, appStatus for the listener that feeds the Spark UI, executorManagement for dynamic allocation, and eventLog for the event log writer.[2]
Each queue has a fixed capacity, spark.scheduler.listenerbus.eventqueue.capacity (default 10000, since 2.3.0), which can be overridden for one queue with spark.scheduler.listenerbus.eventqueue.<queueName>.capacity.[3] When a queue is full, Spark drops events and logs an error saying that a listener is probably too slow to keep up.[4] Dropped events in the appStatus queue show up as missing or stuck jobs and stages in the UI, so listener code should return quickly.
SparkListener
SparkListener is an abstract class with an empty method for each event, so a subclass overrides only what it needs. The methods include onApplicationStart, onApplicationEnd, onJobStart, onJobEnd, onStageSubmitted, onStageCompleted, onTaskStart, onTaskEnd, onExecutorAdded, onExecutorRemoved, onEnvironmentUpdate and onOtherEvent, which receives events from other modules such as SQL execution start and end.[1] The event classes are marked @DeveloperApi, and the underlying trait is documented as an internal interface that might change between releases; the source recommends extending SparkListener or SparkFirehoseListener instead of implementing it directly.[1]
A listener is registered in one of two ways:
- In configuration, with
spark.extraListeners(since 1.3.0), a list of class names that Spark adds to theSparkContextwhen it starts. This catches events from the very start of the application.[3] - In code, with
SparkContext.addSparkListenerandremoveSparkListener.[5]
import org.apache.spark.scheduler.{SparkListener, SparkListenerStageCompleted}
class SlowStageListener extends SparkListener {
override def onStageCompleted(e: SparkListenerStageCompleted): Unit = {
val info = e.stageInfo
for (start <- info.submissionTime; end <- info.completionTime if end - start > 60000) {
println(s"Stage ${info.stageId} (${info.name}) took ${(end - start) / 1000}s")
}
}
}
// spark-submit --conf spark.extraListeners=com.example.SlowStageListener ...
QueryExecutionListener
org.apache.spark.sql.util.QueryExecutionListener is called once per completed DataFrame or SQL action, with onSuccess(funcName, qe, durationNs) or onFailure(funcName, qe, exception). The QueryExecution argument gives access to the logical and physical plans of the query.[6] The interface documentation notes that implementations must be thread-safe, because they can be called from several threads.
A query execution listener is registered per session with spark.listenerManager.register(...), or for every new session with the static setting spark.sql.queryExecutionListeners (since 2.3.0).[6][7] Internally, Spark delivers these callbacks from SQL execution end events on the listener bus.[6]
StreamingQueryListener
StreamingQueryListener (since 2.0.0) receives onQueryStarted, onQueryProgress after each micro-batch, onQueryIdle (since 3.5.0) and onQueryTerminated for Structured Streaming queries.[8] It is registered with spark.streams.addListener(...) or the static setting spark.sql.streaming.streamingQueryListeners (since 2.4.0).[7] PySpark has its own StreamingQueryListener class since 3.4.0, so a streaming listener can be written in Python:[9]
from pyspark.sql.streaming import StreamingQueryListener
class ProgressLogger(StreamingQueryListener):
def onQueryStarted(self, event):
print(f"started {event.id}")
def onQueryProgress(self, event):
p = event.progress
print(f"batch {p.batchId}: {p.numInputRows} rows")
def onQueryIdle(self, event):
pass
def onQueryTerminated(self, event):
print(f"terminated {event.id}")
spark.streams.addListener(ProgressLogger())
What is built on Spark listeners?
- The Spark UI and Spark History Server. Spark's status listener, on the
appStatusqueue, builds the data behind the UI, and the History Server replays event logs through the same kind of listener.[2][10] - The Spark event log, written by
EventLoggingListeneron theeventLogqueue.[2][11] - MLflow autologging for Spark. MLflow's
SparkDataSourceListenerextendsSparkListenerto detect data source reads, so that autologging can record which tables and paths a model was trained on.[12] - OpenLineage lineage collection. The OpenLineage Spark integration is a
SparkListener,io.openlineage.spark.agent.OpenLineageSparkListener, enabled withspark.extraListeners; it reads the events that the SparkContext emits and extracts metadata about jobs and datasets from the RDD and DataFrame dependency graphs.[13]
Spark listener vs Spark plugin
A listener only observes events on the driver. A Spark plugin runs code inside the driver and every executor, can register metrics, and can send messages from executors to the driver. Monitoring tools that need executor-side data use a plugin; tools that only need scheduler events use a listener.[14]
See also
References
- ↑ 1.0 1.1 1.2 SparkListener.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 2.0 2.1 2.2 LiveListenerBus.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 3.0 3.1 config/package.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ AsyncEventQueue.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ SparkContext.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 6.0 6.1 6.2 QueryExecutionListener.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 7.0 7.1 StaticSQLConf.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ StreamingQueryListener.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ listener.py (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ FsHistoryProvider.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ EventLoggingListener.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ SparkDataSourceListener.scala (MLflow v3.18.0). MLflow Project.Retrieved 2026-11-23.
- ↑ Apache Spark integration (OpenLineage 1.55.0). OpenLineage.Retrieved 2026-11-23.
- ↑ SparkPlugin.java (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.