<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nick Grigoriev on Medium]]></title>
        <description><![CDATA[Stories by Nick Grigoriev on Medium]]></description>
        <link>https://medium.com/@grigor60?source=rss-d720daa55a8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2MK5iYwYVyTGeJwdT8AaOA.jpeg</url>
            <title>Stories by Nick Grigoriev on Medium</title>
            <link>https://medium.com/@grigor60?source=rss-d720daa55a8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:37:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@grigor60/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Graceful shutdown for Spark Structured Streaming: Why is it complicated, and how can it be done…]]></title>
            <link>https://medium.com/@grigor60/graceful-shutdown-for-spark-structured-streaming-why-is-it-complicated-and-how-can-it-be-done-bef2674b731c?source=rss-d720daa55a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bef2674b731c</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[spark-streaming]]></category>
            <dc:creator><![CDATA[Nick Grigoriev]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 14:00:01 GMT</pubDate>
            <atom:updated>2024-10-07T17:12:26.070Z</atom:updated>
            <content:encoded><![CDATA[<h3>Graceful shutdown for Spark Structured Streaming: Why is it complicated, and how can it be done right?</h3><p>I wrote this article on habr.com some time ago and want to present it to the English-speaking community.</p><h3>Intro</h3><p>In this article, you find:</p><ol><li>Code for handling the problem.</li><li>Description of the problem.</li><li>Insights into how Spark Structured Streaming works, which I believe are important for understanding the problem.</li><li>There’ll be links to sources in English, with my translation in italics.</li></ol><p>What is not covered in the article:</p><ol><li>Code examples and simple Spark or Spark Structured Streaming applications.</li><li>Detailed explanation of how Spark Structured Streams work.</li><li>Theory on stream data processing: delivery semantics and fault tolerance.</li></ol><p>So, if you’re not familiar with Spark at a basic level, I suggest learning about it beforehand. Otherwise, some references or examples might seem unclear or not obvious. Fortunately, there’s enough information on these topics, as they’re a very popular area in the Big Data world now.</p><h3>Defining the Problem and Participants</h3><p>Let’s start by defining Spark Structured Stream and graceful shutdown.</p><p>Graceful shutdown, also known as correct/standard/error-free termination, is slightly trickier. While many might intuitively understand it, practical experience shows that everyone interprets it slightly differently. To explain the overall concept, I’ll provide an interpretation that suits me and describe what we aim to achieve separately for Structured Stream. Graceful shutdown is when you instruct a program to shut down, wait patiently for some condition to be met in your app as an async call, and then shut down.</p><p>Spark Structured Stream, shouldn&#39;t be confused with Spark Direct Stream. According to the official documentation, it&#39;s a scalable and fault-tolerant data stream processing engine built on the Spark SQL framework. It allows data stream processing to be described in the same way as a static dataset. There are some nuances, but we’ll save that for another article.</p><p>Notably, in the context of Spark Structured Stream, we want to clarify exactly what we need to wait for; it is the completion of the already started micro-batch (group/package) data.</p><h3>Why Do We Need It?</h3><ul><li>Some logic is tied to the stream’s life or completion. For instance, it’s essential to differentiate regular Structured Stream restarts from their falls to set up an Alert manager—an error notification system.</li><li>A logic, possibly resource-intensive, handles falls. For example, double records or other negative consequences might occur when falls happen; their search requires a full scan of the database or file system, and doing so for each Structured Stream restart is wasteful.<br>For instance, I work in a stable environment, and restarting after errors is not usual.</li><li>Stricter Latency SLAs (Service Level Agreements) must not be breached during standard operations, such as schema changes, configuration shifts, or a mere restart on a different cluster. <br>For instance, our SLA is two minutes; the data from its recording source to the destination point should reach within two minutes.<br>In the case of Spark Structured Stream, you can use one-minute intervals. One minute is spent collecting data, and another is spent processing it. Suppose a restart due to changes is commanded at the end of the second minute – the processing minute. If we shut down the application immediately, without waiting for the processing to finish, all the work must be redone. This will naturally lead to a delay blocking the SLA.<br>Significantly, this is undesirable when dealing with schema changes, as there can be many of them.</li></ul><p><strong>It’s crucial to note that the fault tolerance of Structured Stream has no connection to graceful shutdown. Fault tolerance is achieved because all operations and the Structured Stream are idempotent. As a result, it can safely restart after failures. I emphasize that the delivery semantic at the exactly-once level is guaranteed only for Spark Structured Stream operations and states. If the utilized Sink (the destination of your data) does not support write idempotence, restarting a fallen Structured Stream may lead to duplicated records. The native Kafka Sink is a good example. However, in any case, this problem runs much deeper than just a Structured Stream collapse because, in such a case, duplicates may occur when repeating a Spark Task, and retrying a task in Srage is a default behavior for Spark Job.</strong></p><p><em>If you are interested in a correct termination for a sigterm signal, you must ensure the Structured Stream completes before the Spark context terminates. This example will be discussed as the most non-trivial particular case of shutdown.</em></p><h3>Why does shutdown require a separate article and not just a call to the `stop` method?</h3><p>Well, I’ll start with the stop method. From the documentation, two methods control the `stop` behavior of a Structured Stream.</p><pre>query.stop()             // Stop the query (stream)<br>query.awaitTermination() // Block until the query (stream) terminates due to a call to stop() or an error</pre><p>Having two methods, one might guess that <em>stop()</em> is asynchronous. This thought led me to conclude that there shouldn’t be any problem and that the graceful shutdown should be available out of the box.</p><p>But I’ll pretend that I’m smart and read the documentation, and not just recover from errors in production. From the documentation, <em>stop()</em> -&gt;</p><blockquote><em>Stops the execution of this query if it is running. This method blocks until the execution threads have stopped or the timeout has exceeded.</em></blockquote><p>Here, an experienced Java/Scala developer should ideally have been alarmed. Some Thread, which suspiciously reminds us of the Java thread by name, will stop due to a signal. On top of it, another additional method waits for termination. “It’s just <em>thread.interupt()</em>” — you might say, and you’d be right — so there’s no question of any graceful shutdown.</p><p>But to be honest, I’ve gotten so used to various Async/Rx/CSP concepts that it didn’t even occur to me that Stream could be implemented as <em>Thread(() =&gt; while(true) processNextBatch)</em> in one of the most popular Big Data frameworks. And it’s a pity because this is Spark, with many Hadoop inside and ThreadLocal.</p><p>So, I just called these two methods as a pair, as the official documentation suggests. Everything externally was just as it should be—no errors or warning logs. The application was quietly and peacefully shutting down. It was just too fast—within seconds, and my batches were no micro at that point—but about five minutes.</p><p>Something definitely went wrong. Digging through the Spark source code, it’s easy to find that: <br>The <em>stop()</em> method is called <em>sparkSession.sparkContext.cancelJobGroup(runId.toString).</em> <em>cancelJobGroup</em> cancels all tasks that Spark has scheduled or performed during this stream. We go to the Spark UI, and we see that, indeed, the tasks were canceled and a job failed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ig1QKMFqO6qIcUVADH-wxQ.png" /></figure><h3>Solution</h3><p>Here’s a Github <a href="https://gist.github.com/GrigorievNick/bf920e32f70cb1cf8308cd601e415d12">gist</a> with a fully prepared solution running in my production environment for years. <br>The rest of the article will describe this code’s operation. If you’re not a Spark novice, it may be easier to look at the code rather than read the description.</p><p><strong>Higher-level solution description</strong></p><ol><li>Initiate the shutdown signal.</li><li>From this moment, if our stream is active, we wait until the current batch finishes.<br> — How do we know the batch is finished? -&gt; Spark has an interface called StreamingQueryListener which notifies when a batch is completed. It&#39;s important to note this is asynchronous.</li><li>Upon receiving a signal StreamingQueryListener that the batch is finished, we stop the Stream using stream.stop. Becasue Listener is asynchronous, there’s a slim chance that the new batch has already started, but anyway, it will waste only a few seconds of execution. Which I find insignificant in my case.</li></ol><p>For this process, lock/semaphore/queue/rxStream or any other technology for synchronization in a multithreaded environment would be suitable.</p><p>Implementation of initializing a ShutdownHook, which will wait until the stream finishes.</p><pre>class GracefulStopOnShutdownListener(streams: StreamingQueryManager) extends StreamingQueryListener {<br><br>  private val runningQuery = new ConcurrentHashMap[UUID, (Runnable, SynchronousQueue[Boolean])]()<br><br>  override def onQueryStarted(event: StreamingQueryListener.QueryStartedEvent): Unit = {<br>    val stream = streams.get(event.id)<br>    val stopSignalChannel = new SynchronousQueue[Boolean]()<br>    val shutdownHook: Runnable = () =&gt; {<br>      if (stream.isActive) {<br>        val stopSignal = true<br>        stopSignalChannel.put(stopSignal)<br>        stream.stop()<br>        stream.awaitTermination()<br>      }<br>    }<br>    ShutdownHookManager.get().addShutdownHook(shutdownHook, 100, 20, TimeUnit.MINUTES)<br>    runningQuery.put(stream.id, (shutdownHook, stopSignalChannel))<br>    log.info(s&quot;Register shutdown hook for query ${event.id}&quot;)<br>  }</pre><ul><li>`<em>runningQuery: Map[stream -&gt; Shutdown Hook + Stop Signal]</em>`. This structure saves each running Stream, making the process independent for each Structured Stream on the Spark driver.</li><li>`<em>SynchronousQueue.put</em>` — to block the `ShutdownHook` until the batch finishes. This method will put an item in the queue and wait until another Thread picks it up.</li><li>Here, it’s essential not to use a JVM shutdown hook directly. Instead, use the `<em>Hadoop ShutdownHookManager</em>`. Preferably, `Spark ShutdownHookManager` could be used, but it doesn’t have a public API. But Spark` <em>ShutdownHookManager</em>` registers itself in Hadoop with priority 40. So, we need to use the <em>Hadoop </em>`<em>ShutdownHook</em>` with a priority higher than 40. This is important if we specify a priority lower than Spark shutdown hooks. Then, the Spark context will shut down before our stream, leading to the Stream&#39;s collapse and its current tasks.</li></ul><p>Next, each batch must release our shutdown hook but not get blocked if there hasn’t been a sigterm signal.</p><pre>override def onQueryProgress(event: StreamingQueryListener.QueryProgressEvent): Unit = {<br>    val (_, stopSignalChannel) = runningQuery.get(event.progress.id)<br>    stopSignalChannel.poll()<br>  }</pre><ul><li>`<em>SynchronousQueue.poll</em>` — non-blocking. It will either take an element from the queue or get null. This will unblock Put from the Shutdown Hook but not block the Listener if there is no <a href="https://ru.wikipedia.org/wiki/SIGTERM">sigterm</a> signal.</li></ul><p>In general, everything is now prepared and will work, but there is a scenario that wasn’t considered:</p><ul><li>The Stream had started — registered the hook, but crashed with an error or was forcibly stopped before the <a href="https://ru.wikipedia.org/wiki/SIGTERM">sigterm</a> arrived.</li></ul><p>Hence, we need to remove the ShutdownHook in this case. The last method, `<em>onQueryTerminated</em>,` will help us.</p><pre>override def onQueryTerminated(event: StreamingQueryListener.QueryTerminatedEvent): Unit = {<br>    val (shutdownHook, stopSignalChannel) = runningQuery.remove(event.id)<br>    if (!ShutdownHookManager.get().isShutdownInProgress) ShutdownHookManager.get().removeShutdownHook(shutdownHook)<br>    stopSignalChannel.poll()<br>  }</pre><p>* Remove our stream from the Listener to clean up resources.<br>* Remove `<em>ShutdownHook,</em>` so it does not block the application during <a href="https://ru.wikipedia.org/wiki/SIGTERM">sigterm</a> later.<br>* Release the synchronization just in case. Someone might have gotten blocked on it before we removed the hook after completing the last batch.</p><h3>Conclusion</h3><p>The same GitHub <a href="https://gist.github.com/GrigorievNick/bf920e32f70cb1cf8308cd601e415d12">gist</a> that contains the solution also includes a `Main class` that allows you to reproduce the error and visualize the solution using <a href="https://docs.faculty.ai/how_to/spark/local_spark.html">Spark in local mode</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bef2674b731c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>