<?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 Seonggil Jeong on Medium]]></title>
        <description><![CDATA[Stories by Seonggil Jeong on Medium]]></description>
        <link>https://medium.com/@seonggil?source=rss-9e5e0974a617------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tp6F0K-KxbNS7HqW-C0b_w.jpeg</url>
            <title>Stories by Seonggil Jeong on Medium</title>
            <link>https://medium.com/@seonggil?source=rss-9e5e0974a617------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:01:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seonggil/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[Apache Spark Memory Deep Dive: The Betrayal of Broadcast Variables and Resolving OOM]]></title>
            <link>https://medium.com/towards-data-engineering/apache-spark-memory-deep-dive-the-betrayal-of-broadcast-variables-and-resolving-oom-a23f4de9b713?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/a23f4de9b713</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 10:12:49 GMT</pubDate>
            <atom:updated>2026-07-05T02:42:02.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DFE3Ouzru8L5yJF9.png" /></figure><h3>The Catalyst: How Simple Logic Caused a Pipeline Bottleneck</h3><p>Recently, while building a data pipeline based on Apache Spark, I had to develop logic to extract and aggregate non-standardized country names (e.g., Korea, Ko, ko) into standardized country codes (e.g., Korea).</p><p>The logic itself was incredibly simple. It involved defining mapping rules as a Python dictionary using a library, and replacing the values via a UDF (.map).<br>However, as the volume of data grew, this simple dictionary mapping logic became a severe bottleneck, hogging Executor memory and causing massive performance degradation.</p><blockquote>This led to a lingering question: <em>“Broadcasted variables are stored once per Executor in the Storage Memory area. But since they are deserialized when used by Python workers, doesn’t the data get duplicated in memory as many times as the number of workers?”</em></blockquote><p>To resolve and verify this, I brainstormed three different approaches for passing dictionary data to the Executors:</p><ol><li><strong>Encapsulating as a Python Closure variable</strong> and calling it inside .map</li><li><strong>Explicitly passing it as a Spark Broadcast Variable.</strong></li><li><strong>Converting the mapping rules into a DataFrame</strong> and performing a Broadcast Hash Join (BHJ) at the JVM level.</li></ol><p>In this post, I will share how I set up hypotheses for these three methods and dug into the internal logs to understand how data is serialized/deserialized between the Driver and Executors in a PySpark environment, and how memory is ultimately consumed.</p><p><em>You can find the full code at the bottom of this post.</em></p><h3>Test Environment</h3><blockquote><strong>Spark:</strong> 3.5.1 (PySpark)<br><strong>Python:</strong> 3.12<br><strong>Cluster:</strong> local-cluster[2,2,1024] (2 Executors, 2 Cores, processing 16 partitions)</blockquote><h3>Background Knowledge: PySpark’s Execution Structure and Memory Sharing Limits</h3><p>Because PySpark’s Executor processes are JVM-based, they cannot execute Python code directly. Therefore, Executors must exchange data with separate Python Worker processes via local socket communication.</p><h4>PySpark Python UDF Workflow</h4><ol><li>When the JVM Executor receives a task, it checks if a pyspark.daemon process exists on the node.</li><li>The Executor requests the daemon to spawn a worker. The pyspark.daemon calls Linux&#39;s os.fork() to clone itself and create a Python Worker Process.</li></ol><ul><li><strong>Here, I formulated a hypothesis:</strong> <em>If we pass a massive dictionary to the Python worker, can we benefit from Linux’s COW (Copy-On-Write) and share the memory?</em></li><li><strong>To give you the conclusion first:</strong> <strong>it is impossible.</strong> The pyspark.daemon does not hold the actual data at the time it forks. The data is individually loaded only after the worker has been created.</li></ul><p>So, how does the memory footprint of the Python worker change depending on the <em>method</em> used to pass the data? To find out, I wrote a custom class (Tracker) to trace memory usage (RSS) and Object IDs, and began my verification.</p><h3>Hypothesis Test 1: The Memory Lifecycle of Python Closure Variables</h3><p>This is the most common anti-pattern: referencing an external variable (Closure). When a globally declared large dictionary or object is directly referenced inside a map function, how does Spark handle it?</p><pre>spark = (<br>    SparkSession.builder.master(&quot;local-cluster[2,2,1024]&quot;)<br>    .appName(&quot;ClosureTest&quot;)<br>    .config(&quot;spark.python.worker.reuse&quot;, &quot;true&quot;)<br>    .getOrCreate()<br>)<br>sc = spark.sparkContext<br>closure_obj = Tracker(&quot;Closure&quot;, payload_size_mb=100)<br><br>...<br><br>def task(partition_idx, iterator):<br>    before = rss_mb()<br>    obj = closure_obj<br>    obj.counter += 1<br>    after = rss_mb()<br>    <br>    list(iterator)<br>    <br>    return [<br>        {<br>          ...<br>        }<br>    ]<br><br>result = rdd.mapPartitionsWithIndex(task).collect()</pre><p>At first, I suspected, <em>“When hundreds of Tasks (partitions) are executed, does the Driver send the variable via RPC communication every single time?”</em> However, after digging into Spark’s DAGScheduler logs, my assumption was only half right.</p><pre># Tracker Log<br><br>    DRIVER<br>    pid=2077<br>    host=Seonggils-MacBook-Pro.local<br><br>            CREATE<br>            mode=Closure<br>            pid=2077<br>            host=Seonggils-MacBook-Pro.local<br>            obj_id=4528186352<br><br>            SERIALIZE<br>            mode=Closure<br>            serialize_idx=1<br>            pid=2077<br>            host=Seonggils-MacBook-Pro.local<br>            obj_id=4528186352<br>            size=100.00MB<br><br>...<br><br># DAGScheduler Log<br># --- Executor ---<br><br>INFO BlockManagerInfo: Added broadcast_0_python on disk on &lt;ip&gt;:50002 (size: 100.0 MiB)<br>INFO BlockManagerInfo: Added broadcast_0_python on disk on &lt;ip&gt;:50003 (size: 100.0 MiB)</pre><p>To prevent Driver network bottlenecks caused by sending thousands of tasks via RPC, Spark optimizes this by creating a Broadcast variable out of the serialized byte array of the Task and Closure (taskBinary), sending it to each Executor (JVM) exactly once.</p><p><strong>However, the real problem started in the Python Worker process.</strong></p><pre># Closure Result<br><br>================================================================================<br>RESULT<br>================================================================================<br>{&#39;partition&#39;: 0, &#39;pid&#39;: 9044, &#39;object_id&#39;: 4452912544, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.15625, &#39;rss_after&#39;: 234.21875, &#39;rss_delta&#39;: 0.0625}<br>{&#39;partition&#39;: 1, &#39;pid&#39;: 9045, &#39;object_id&#39;: 4452912544, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.21875, &#39;rss_after&#39;: 234.265625, &#39;rss_delta&#39;: 0.046875}<br>{&#39;partition&#39;: 2, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4398518144, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.1875, &#39;rss_after&#39;: 234.25, &#39;rss_delta&#39;: 0.0625}<br>{&#39;partition&#39;: 3, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4398518144, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.21875, &#39;rss_after&#39;: 234.28125, &#39;rss_delta&#39;: 0.0625}<br>{&#39;partition&#39;: 4, &#39;pid&#39;: 9042, &#39;object_id&#39;: 4555782432, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.1875, &#39;rss_after&#39;: 234.234375, &#39;rss_delta&#39;: 0.046875}<br>{&#39;partition&#39;: 5, &#39;pid&#39;: 9043, &#39;object_id&#39;: 4454748032, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.21875, &#39;rss_after&#39;: 234.265625, &#39;rss_delta&#39;: 0.046875}<br>{&#39;partition&#39;: 6, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506131472, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.328125, &#39;rss_after&#39;: 272.328125, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 7, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506131424, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.40625, &#39;rss_after&#39;: 272.40625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 8, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506128976, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.765625, &#39;rss_after&#39;: 272.765625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 9, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506128928, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.890625, &#39;rss_after&#39;: 272.890625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 10, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506130752, &#39;counter&#39;: 1, &#39;rss_before&#39;: 273.0, &#39;rss_after&#39;: 273.0, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 11, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506128112, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.859375, &#39;rss_after&#39;: 272.859375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 12, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506130176, &#39;counter&#39;: 1, &#39;rss_before&#39;: 273.15625, &#39;rss_after&#39;: 273.15625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 13, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506130560, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.859375, &#39;rss_after&#39;: 272.859375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 14, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506129552, &#39;counter&#39;: 1, &#39;rss_before&#39;: 273.328125, &#39;rss_after&#39;: 273.328125, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 15, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506130704, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.859375, &#39;rss_after&#39;: 272.859375, &#39;rss_delta&#39;: 0.0}</pre><p>Even though worker reuse is enabled (spark.python.worker.reuse=true) and multiple partitions are processed on the same PID (9040), the Object ID changes for every single partition, and the Counter is always initialized to 1.</p><p>The reason lies in PySpark’s deserialization mechanism.<br>Every time a Task is assigned from the JVM to the Python Worker, the worker uses cloudpickle.loads() to newly <strong>unpickle (deserialize)</strong> the received closure byte array and load it into memory. In short, if you have a 300MB closure and 50 partitions (Tasks) to process, the Python worker creates and discards that 300MB object 50 times. This is the primary culprit behind extreme Garbage Collection (GC) overhead and OOM errors.</p><h3>Hypothesis Test 2: Broadcast Variable — Caching Logic at the Worker Level</h3><p>So, how does the Worker’s behavior change if we explicitly use a Broadcast Variable?</p><pre>spark: SparkSession = (<br>    SparkSession.builder.master(&quot;local-cluster[2,2,1024]&quot;)<br>    .appName(&quot;BroadcastTest&quot;)<br>    .config(&quot;spark.python.worker.reuse&quot;, &quot;true&quot;)<br>    .getOrCreate()<br>)<br>sc = spark.sparkContext<br>broadcast_obj = Tracker(&quot;Broadcast&quot;, payload_size_mb=100)<br>bc = sc.broadcast(broadcast_obj)<br><br>...<br><br>def task(partition_idx, iterator):<br>    before = rss_mb()<br>    obj = bc.value<br>    obj.counter += 1<br>    after = rss_mb()<br>    <br>    list(iterator)<br>    <br>    return [<br>        {<br>          ...<br>        }<br>    ]<br><br>result = rdd.mapPartitionsWithIndex(task).collect()</pre><p>The results showed a stark difference. Looking at the same PID (Worker), memory (RSS) <strong>only increased once when the broadcast variable was initially loaded. </strong>For all subsequent partitions processed by that worker, the memory delta was 0.<br>Furthermore, the Object ID remained identical, and the Counter value accumulated, proving that the object was perfectly cached in memory and reused.</p><pre># Broadcast Result<br><br>================================================================================<br>RESULT<br>================================================================================<br>{&#39;partition&#39;: 0, &#39;pid&#39;: 9108, &#39;object_id&#39;: 4566676736, &#39;counter&#39;: 1, &#39;rss_before&#39;: 30.640625, &#39;rss_after&#39;: 133.984375, &#39;rss_delta&#39;: 103.34375}<br>{&#39;partition&#39;: 1, &#39;pid&#39;: 9109, &#39;object_id&#39;: 4565405856, &#39;counter&#39;: 1, &#39;rss_before&#39;: 30.8125, &#39;rss_after&#39;: 134.171875, &#39;rss_delta&#39;: 103.359375}<br>{&#39;partition&#39;: 2, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 1, &#39;rss_before&#39;: 30.90625, &#39;rss_after&#39;: 134.359375, &#39;rss_delta&#39;: 103.453125}<br>{&#39;partition&#39;: 3, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 1, &#39;rss_before&#39;: 30.8125, &#39;rss_after&#39;: 134.28125, &#39;rss_delta&#39;: 103.46875}<br>{&#39;partition&#39;: 4, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 2, &#39;rss_before&#39;: 172.515625, &#39;rss_after&#39;: 172.515625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 5, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 2, &#39;rss_before&#39;: 172.59375, &#39;rss_after&#39;: 172.59375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 6, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 3, &#39;rss_before&#39;: 173.09375, &#39;rss_after&#39;: 173.09375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 7, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 3, &#39;rss_before&#39;: 173.0625, &#39;rss_after&#39;: 173.0625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 8, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 4, &#39;rss_before&#39;: 173.171875, &#39;rss_after&#39;: 173.171875, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 9, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 4, &#39;rss_before&#39;: 173.109375, &#39;rss_after&#39;: 173.109375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 10, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 5, &#39;rss_before&#39;: 173.234375, &#39;rss_after&#39;: 173.234375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 11, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 5, &#39;rss_before&#39;: 173.1875, &#39;rss_after&#39;: 173.1875, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 12, &#39;pid&#39;: 9109, &#39;object_id&#39;: 4565405856, &#39;counter&#39;: 2, &#39;rss_before&#39;: 172.546875, &#39;rss_after&#39;: 172.546875, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 13, &#39;pid&#39;: 9108, &#39;object_id&#39;: 4566676736, &#39;counter&#39;: 2, &#39;rss_before&#39;: 172.40625, &#39;rss_after&#39;: 172.40625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 14, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 6, &#39;rss_before&#39;: 173.234375, &#39;rss_after&#39;: 173.234375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 15, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 6, &#39;rss_before&#39;: 173.1875, &#39;rss_after&#39;: 173.1875, &#39;rss_delta&#39;: 0.0}</pre><p>This happens because, internally in PySpark, when .value is called for the first time, it reads the broadcast file from the local disk, deserializes it, and saves it in the worker&#39;s global context (_broadcastRegistry). The inefficiency of recreating the object for every partition (like the closure method) is entirely eliminated.</p><p>However, I could confirm my initial suspicion: <strong>the data is still duplicated in memory as many times as there are Python workers (i.e., the number of cores).</strong> <em>(Note: If you disable Python worker reuse with </em><em>&quot;spark.python.worker.reuse&quot;: &quot;false&quot;, it behaves identically to the Closure variable with the counter remaining at 1).</em></p><h3>Hypothesis Test 3: The Ultimate Answer for Large-Scale Data — Broadcast Hash Join (BHJ)</h3><p>Finally, I tested the scenario where, instead of passing the dictionary as a Python object, I converted it into a DataFrame and executed a Broadcast Hash Join through the Spark SQL engine.</p><p>In this case, the data <strong>never crosses over into the Python worker’s memory space.</strong> Spark’s physical execution engine (Tungsten) utilizes its own internal memory format (UnsafeRow) to process the join entirely within the JVM.</p><p><strong>Executor Heap Histogram Analysis Results:</strong></p><pre># Executor Heap Histogram<br># Rank | Instances | Bytes | Class Name<br><br>1882 | 1 | 24 | org.apache.spark.sql.execution.joins.LongHashedRelation</pre><p>As the results show, exactly <strong>one instance</strong> of the LongHashedRelation object is created in the JVM heap space of each Executor, and all Cores (Tasks) share it.</p><p>This is the most ideal state: there is absolutely zero serialization/deserialization communication cost between Python and the JVM, and the data is not duplicated per core.</p><h3>Conclusion &amp; Summary</h3><p>Based on the logging and code analysis above, we can outline the following architectural strategies for passing reference metadata in a PySpark environment:</p><p>If you need to transmit Column/Row-shaped data or large datasets, you should strongly consider processing it with a <strong>Broadcast Hash Join</strong> depending on the context, rather than simply passing it as a <strong>Broadcast Variable</strong>.</p><p><strong>Closure Variable</strong></p><ul><li><strong>Network Transmission:</strong> Broadcasted once to the JVM.</li><li><strong>Python Memory Load:</strong> Freshly unpickled for <em>every</em> Task (partition).</li><li><strong>Drawbacks:</strong> The object is created and destroyed repeatedly as many times as the number of partitions processed (causes extreme GC).</li></ul><p><strong>Broadcast Variable</strong></p><ul><li><strong>Network Transmission:</strong> Broadcasted once to the JVM.</li><li><strong>Python Memory Load:</strong> Loaded exactly once per Worker Process (PID).</li><li><strong>Drawbacks:</strong> Data is replicated in memory according to the number of Cores (Workers).</li></ul><p><strong>Broadcast Hash Join (BHJ)</strong></p><ul><li><strong>Network Transmission:</strong> Broadcasted once to the JVM.</li><li><strong>Python Memory Load:</strong> Data is <em>never</em> sent to the Python Worker.</li><li><strong>Drawbacks:</strong> Network I/O occurs when managing it as a table; puts a burden on the Driver if dynamically generated.</li></ul><h3>References</h3><ul><li><strong>Task Broadcast Logic in DAGScheduler:<br></strong>The optimization logic inside submitMissingTasks that broadcasts the serialized Task Binary object just once to prevent Driver network bottlenecks.</li></ul><p><a href="https://github.com/apache/spark/blob/master/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala">spark/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala at master · apache/spark</a></p><ul><li><strong>Process Forking via pyspark.daemon:<br></strong>Checking the behavior of the background daemon, which takes requests from the JVM Executor and spawns the actual Python worker processes via Linux’s os.fork().</li></ul><p><a href="https://github.com/apache/spark/blob/master/python/pyspark/daemon.py">spark/python/pyspark/daemon.py at master · apache/spark</a></p><ul><li><strong>Python Worker Deserialization (Unpickle):<br></strong>How the Python worker, upon receiving a Task from the JVM, unpickles the byte array back into a Python object (using cloudpickle, etc.) inside the read_command function to load it into memory.</li></ul><p><a href="https://github.com/apache/spark/blob/master/python/pyspark/worker.py">spark/python/pyspark/worker.py at master · apache/spark</a></p><ul><li><strong>LongHashedRelation in Broadcast Hash Join:<br></strong>The hash table structure that the Tungsten engine instantiates just once within the JVM to process joins and reuse across tasks.</li></ul><p><a href="https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/HashedRelation.scala">spark/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/HashedRelation.scala at master · apache/spark</a></p><h3>Full Code</h3><ul><li>tracker.py</li></ul><pre>import os<br>import pickle<br>import socket<br><br><br>class Tracker:<br>    serialize_count = 0<br><br>    def __init__(self, mode_name, payload_size_mb=100):<br><br>        self.mode_name = mode_name<br><br>        self.counter = 0<br><br>        self.payload = b&quot;x&quot; * payload_size_mb * 1024 * 1024<br><br>        print(<br>            f&quot;&quot;&quot;<br>            CREATE<br>            mode={mode_name}<br>            pid={os.getpid()}<br>            host={socket.gethostname()}<br>            obj_id={id(self)}<br>            &quot;&quot;&quot;<br>        )<br><br>    def __getstate__(self):<br><br>        Tracker.serialize_count += 1<br><br>        size_mb = len(pickle.dumps(self.__dict__)) / 1024 / 1024<br><br>        print(<br>            f&quot;&quot;&quot;<br>            SERIALIZE<br>            mode={self.mode_name}<br>            serialize_idx={Tracker.serialize_count}<br>            pid={os.getpid()}<br>            host={socket.gethostname()}<br>            obj_id={id(self)}<br>            size={size_mb:.2f}MB<br>            &quot;&quot;&quot;<br>        )<br><br>        return self.__dict__</pre><ul><li>test_closure.py</li></ul><pre>import os<br>import socket<br><br>import psutil<br>from tracker import Tracker<br><br>from pyspark.sql import SparkSession<br><br><br>def rss_mb():<br>    return psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024<br><br><br>spark = (<br>    SparkSession.builder.master(&quot;local-cluster[2,2,1024]&quot;)<br>    .appName(&quot;ClosureTest&quot;)<br>    .config(&quot;spark.python.worker.reuse&quot;, &quot;true&quot;)<br>    .getOrCreate()<br>)<br><br>sc = spark.sparkContext<br>sc.setLogLevel(&quot;DEBUG&quot;)<br><br>sc.addPyFile(&quot;tracker.py&quot;)<br><br>print(<br>    f&quot;&quot;&quot;<br>    DRIVER<br>    pid={os.getpid()}<br>    host={socket.gethostname()}<br>    &quot;&quot;&quot;<br>)<br><br>closure_obj = Tracker(&quot;Closure&quot;, payload_size_mb=1)<br><br>rdd = sc.parallelize(range(16), 16)<br><br><br>def task(partition_idx, iterator):<br><br>    before = rss_mb()<br><br>    obj = closure_obj<br><br>    obj.counter += 1<br><br>    after = rss_mb()<br><br>    list(iterator)<br><br>    return [<br>        {<br>            &quot;partition&quot;: partition_idx,<br>            &quot;pid&quot;: os.getpid(),<br>            &quot;host&quot;: socket.gethostname(),<br>            &quot;object_id&quot;: id(obj),<br>            &quot;counter&quot;: obj.counter,<br>            &quot;rss_before&quot;: before,<br>            &quot;rss_after&quot;: after,<br>            &quot;rss_delta&quot;: after - before,<br>        }<br>    ]<br><br><br>result = rdd.mapPartitionsWithIndex(task).collect()<br><br>print(&quot;\n&quot;)<br>print(&quot;=&quot; * 80)<br>print(&quot;RESULT&quot;)<br>print(&quot;=&quot; * 80)<br><br>for row in sorted(result, key=lambda x: x[&quot;partition&quot;]):<br>    print(row)<br><br>spark.stop()</pre><ul><li>test_broadcast.py</li></ul><pre>import os<br>import socket<br><br>import psutil<br>from tracker import Tracker<br><br>from pyspark.sql import SparkSession<br><br><br>def rss_mb():<br>    return psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024<br><br><br>spark = (<br>    SparkSession.builder.master(&quot;local-cluster[2,2,1024]&quot;)<br>    .appName(&quot;ClosureTest&quot;)<br>    .config(&quot;spark.python.worker.reuse&quot;, &quot;true&quot;)<br>    .getOrCreate()<br>)<br><br>sc = spark.sparkContext<br>sc.setLogLevel(&quot;DEBUG&quot;)<br><br>sc.addPyFile(&quot;tracker.py&quot;)<br><br>print(<br>    f&quot;&quot;&quot;<br>    DRIVER<br>    pid={os.getpid()}<br>    host={socket.gethostname()}<br>    &quot;&quot;&quot;<br>)<br><br>closure_obj = Tracker(&quot;Closure&quot;, payload_size_mb=1)<br><br>rdd = sc.parallelize(range(16), 16)<br><br><br>def task(partition_idx, iterator):<br><br>    before = rss_mb()<br><br>    obj = closure_obj<br><br>    obj.counter += 1<br><br>    after = rss_mb()<br><br>    list(iterator)<br><br>    return [<br>        {<br>            &quot;partition&quot;: partition_idx,<br>            &quot;pid&quot;: os.getpid(),<br>            &quot;host&quot;: socket.gethostname(),<br>            &quot;object_id&quot;: id(obj),<br>            &quot;counter&quot;: obj.counter,<br>            &quot;rss_before&quot;: before,<br>            &quot;rss_after&quot;: after,<br>            &quot;rss_delta&quot;: after - before,<br>        }<br>    ]<br><br><br>result = rdd.mapPartitionsWithIndex(task).collect()<br><br>print(&quot;\n&quot;)<br>print(&quot;=&quot; * 80)<br>print(&quot;RESULT&quot;)<br>print(&quot;=&quot; * 80)<br><br>for row in sorted(result, key=lambda x: x[&quot;partition&quot;]):<br>    print(row)<br><br>spark.stop()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a23f4de9b713" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/apache-spark-memory-deep-dive-the-betrayal-of-broadcast-variables-and-resolving-oom-a23f4de9b713">Apache Spark Memory Deep Dive: The Betrayal of Broadcast Variables and Resolving OOM</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark Memory Deep Dive: 브로드캐스트 변수의 배신과 OOM 해결기]]></title>
            <link>https://medium.com/@seonggil/apache-spark-memory-deep-dive-%EB%B8%8C%EB%A1%9C%EB%93%9C%EC%BA%90%EC%8A%A4%ED%8A%B8-%EB%B3%80%EC%88%98%EC%9D%98-%EB%B0%B0%EC%8B%A0%EA%B3%BC-oom-%ED%95%B4%EA%B2%B0%EA%B8%B0-78bd682f67c0?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/78bd682f67c0</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 16:07:44 GMT</pubDate>
            <atom:updated>2026-07-05T02:41:43.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*L2HHtwiPCTX8pXxs.png" /></figure><h3>발단: 단순한 로직이 불러온 파이프라인 병목</h3><p>최근 Apache Spark기반의 데이터 파이프라인을 구축 과정에서, 내 비정형화된 국가명(예: Korea, Ko, ko 등)을 정형화된 국가 코드(Korea)로 추출하고 집계하는 로직을 개발하게 되었습니다.</p><p>논리 자체는 매우 단순했습니다. 라이브러리를 활용해 Python 딕셔너리 형태의 매핑 규칙을 정의하고, 이를 UDF(.map)을 통해 치환하는 것입니다.<br>하지만 처리해야 할 데이터가 많아지자, 이 단순한 딕셔너리 매핑 로직이 Executor의 메모리를 점유하고 심각한 성능 지연을 유발하는 병목 지점이 되었습니다.</p><blockquote>여기서 생긴 궁금증은…<br><strong>“브로드캐스팅된 변수는 Storage Memory 영역에 Executor 단위로 한 번 저장되지만, 파이썬 워커에서 해당 변수를 사용할 때 역직렬화되기 때문에 워커 수만큼 데이터가 복제되지 않을까?”</strong></blockquote><p>이를 해결, 검증하기 위해 딕셔너리 데이터를 각 Executor에 전달하는 방식을 세 가지로 나누어 고민했습니다.</p><ol><li><strong>Closure 변수</strong>로 캡슐화하여 .map 내부에서 호출하는 방식</li><li><strong>Spark Broadcast Variable</strong>로 선언하여 명시적으로 전달하는 방식</li><li>매핑 룰 자체를 DataFrame으로 생성하여 JVM 레벨에서 Broadcast Hash Join (BHJ)을 수행하는 방식</li></ol><p>이 글에서는 위 세 가지 방식이 PySpark 환경의 Driver와 Executor 사이에서 어떻게 직렬화/역직렬화되며, 메모리를 어떻게 점유하는지 직접 가설을 세우고 로그를 통해 내부 동작(Internals)을 파헤친 과정을 공유합니다.</p><p><em>글 하단에서 전체 코드를 확인할 수 있습니다.</em></p><h4><strong>테스트 환경</strong></h4><blockquote>Spark: 3.5.1 (PySpark)<br>Python: 3.12<br>Cluster: local-cluster[2,2,1024] (Executor 2개, 코어 2개, 16 파티션 처리)</blockquote><h3>배경 지식: PySpark의 실행 구조와 메모리 공유의 한계</h3><p>PySpark의 Executor 프로세스는 JVM 기반이므로 Python 코드를 직접 실행할 수 없습니다. 따라서 Executor는 로컬 소켓(Socket) 통신을 통해 별도의 Python Worker 프로세스와 데이터를 주고받아야 합니다.</p><h4><strong>PySpark Python UDF Workflow</strong></h4><ol><li>JVM Executor가 태스크를 수신하면, 노드에 pyspark.daemon 프로세스가 있는지 확인합니다.</li><li>Executor는 데몬에게 워커 생성을 요청하고, pyspark.daemon은 Linux의 os.fork()를 호출하여 자신을 복제한 <strong>Python Worker Process</strong>를 생성합니다.</li></ol><p>여기서 한 가지 <strong>가설</strong>을 세웠습니다. 만약 거대한 딕셔너리를 파이썬 워커로 넘긴다면, <strong>Linux의 COW(Copy-On-Write)</strong> 이점을 얻어 메모리가 공유될까?<br>결론부터 말하자면 불가능합니다. pyspark.daemon은 포크되는 시점에 실제 데이터를 들고 있지 않으며, 데이터는 워커가 생성된 후 개별적으로 로드되기 때문입니다.</p><p>그렇다면 데이터가 전달되는 ‘방식’에 따라 파이썬 워커의 메모리 상태는 어떻게 달라질까요? 이를 확인하기 위해 메모리 점유량(RSS)과 객체 ID를 추적하는 커스텀 클래스(Tracker)를 작성하여 검증에 돌입했습니다.</p><h3>가설 검증 1: Python Closure 변수의 메모리 생명 주기</h3><p>가장 흔하게 실수하는 패턴인 외부 변수(Closure) 참조 방식입니다.<br>전역으로 선언된 큰 딕셔너리나 객체를 map 함수 내부에서 바로 참조할 때 Spark는 이를 어떻게 처리할까요?</p><pre>spark = (<br>    SparkSession.builder.master(&quot;local-cluster[2,2,1024]&quot;)<br>    .appName(&quot;ClosureTest&quot;)<br>    .config(&quot;spark.python.worker.reuse&quot;, &quot;true&quot;)<br>    .getOrCreate()<br>)<br>sc = spark.sparkContext<br>closure_obj = Tracker(&quot;Closure&quot;, payload_size_mb=100)<br><br>...<br><br>def task(partition_idx, iterator):<br><br>    before = rss_mb()<br><br>    obj = closure_obj<br><br>    obj.counter += 1<br><br>    after = rss_mb()<br><br>    list(iterator)<br><br>    return [<br>        {<br>          ...<br>        }<br>    ]<br><br><br>result = rdd.mapPartitionsWithIndex(task).collect()</pre><p>처음에는 <em>“수백 개의 Task(파티션)가 실행될 때마다 Driver가 일일이 RPC 통신으로 변수를 쏴주지 않을까?”</em>라고 의심했습니다. 하지만 Spark의 DAGScheduler 로그를 뜯어본 결과, 제 예상은 반만 맞았습니다.</p><pre># Tracker Log<br><br>    DRIVER<br>    pid=2077<br>    host=Seonggils-MacBook-Pro.local<br><br>            CREATE<br>            mode=Closure<br>            pid=2077<br>            host=Seonggils-MacBook-Pro.local<br>            obj_id=4528186352<br><br>            SERIALIZE<br>            mode=Closure<br>            serialize_idx=1<br>            pid=2077<br>            host=Seonggils-MacBook-Pro.local<br>            obj_id=4528186352<br>            size=100.00MB<br><br>...<br><br># DAGScheduler Log<br># --- Executor ---<br><br>INFO BlockManagerInfo: Added broadcast_0_python on disk on &lt;ip&gt;:50002 (size: 100.0 MiB)<br>INFO BlockManagerInfo: Added broadcast_0_python on disk on &lt;ip&gt;:50003 (size: 100.0 MiB)</pre><p>Spark는 수많은 Task를 RPC로 전송할 때 발생하는 Driver의 네트워크 병목을 막기 위해, Task와 클로저가 직렬화된 바이트 배열(taskBinary) 자체를 <strong>Broadcast 변수로 만들어 각 Executor(JVM)에 단 한 번만 전송</strong>하는 최적화를 수행하고 있었습니다.</p><p>하지만 문제는 Python Worker 프로세스에서 시작되었습니다.</p><pre># Closure Result<br><br>================================================================================<br>RESULT<br>================================================================================<br>{&#39;partition&#39;: 0, &#39;pid&#39;: 9044, &#39;object_id&#39;: 4452912544, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.15625, &#39;rss_after&#39;: 234.21875, &#39;rss_delta&#39;: 0.0625}<br>{&#39;partition&#39;: 1, &#39;pid&#39;: 9045, &#39;object_id&#39;: 4452912544, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.21875, &#39;rss_after&#39;: 234.265625, &#39;rss_delta&#39;: 0.046875}<br>{&#39;partition&#39;: 2, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4398518144, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.1875, &#39;rss_after&#39;: 234.25, &#39;rss_delta&#39;: 0.0625}<br>{&#39;partition&#39;: 3, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4398518144, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.21875, &#39;rss_after&#39;: 234.28125, &#39;rss_delta&#39;: 0.0625}<br>{&#39;partition&#39;: 4, &#39;pid&#39;: 9042, &#39;object_id&#39;: 4555782432, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.1875, &#39;rss_after&#39;: 234.234375, &#39;rss_delta&#39;: 0.046875}<br>{&#39;partition&#39;: 5, &#39;pid&#39;: 9043, &#39;object_id&#39;: 4454748032, &#39;counter&#39;: 1, &#39;rss_before&#39;: 234.21875, &#39;rss_after&#39;: 234.265625, &#39;rss_delta&#39;: 0.046875}<br>{&#39;partition&#39;: 6, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506131472, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.328125, &#39;rss_after&#39;: 272.328125, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 7, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506131424, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.40625, &#39;rss_after&#39;: 272.40625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 8, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506128976, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.765625, &#39;rss_after&#39;: 272.765625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 9, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506128928, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.890625, &#39;rss_after&#39;: 272.890625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 10, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506130752, &#39;counter&#39;: 1, &#39;rss_before&#39;: 273.0, &#39;rss_after&#39;: 273.0, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 11, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506128112, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.859375, &#39;rss_after&#39;: 272.859375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 12, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506130176, &#39;counter&#39;: 1, &#39;rss_before&#39;: 273.15625, &#39;rss_after&#39;: 273.15625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 13, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506130560, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.859375, &#39;rss_after&#39;: 272.859375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 14, &#39;pid&#39;: 9040, &#39;object_id&#39;: 4506129552, &#39;counter&#39;: 1, &#39;rss_before&#39;: 273.328125, &#39;rss_after&#39;: 273.328125, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 15, &#39;pid&#39;: 9041, &#39;object_id&#39;: 4506130704, &#39;counter&#39;: 1, &#39;rss_before&#39;: 272.859375, &#39;rss_after&#39;: 272.859375, &#39;rss_delta&#39;: 0.0}</pre><p>워커 재사용 설정(spark.python.worker.reuse=true)이 되어 있어 동일한 PID(9040) 위에서 여러 파티션이 처리됨에도 불구하고, <strong>Object ID가 매 파티션마다 달라지고 </strong><strong>Counter는 항상 1로 초기화</strong>되었습니다.</p><p>이유는 PySpark의 역직렬화 메커니즘 때문입니다.<br>JVM에서 Python Worker로 Task가 할당될 때마다, 워커는 전달받은 클로저 바이트 배열을 cloudpickle.loads()를 통해 <strong>매번 새로 Unpickle(역직렬화)하여 메모리에 적재</strong>합니다. 즉, 300MB 크기의 클로저가 있고 50개의 파티션(Task)을 처리해야 한다면, 파이썬 워커는 300MB 객체를 50번이나 메모리에 생성하고 버리기를 반복합니다. 이는 극심한 가비지 컬렉션(GC) 오버헤드와 OOM의 주범이 됩니다.</p><h3>가설 검증 2: Broadcast Variable: 워커 레벨의 캐싱 로직</h3><p>그렇다면 Broadcast Variable을 명시적으로 사용하면 Worker 측의 동작은 어떻게 달라질까요?</p><pre>spark: SparkSession = (<br>    SparkSession.builder.master(&quot;local-cluster[2,2,1024]&quot;)<br>    .appName(&quot;BroadcastTest&quot;)<br>    .config(&quot;spark.python.worker.reuse&quot;, &quot;true&quot;)<br>    .getOrCreate()<br>)<br>sc = spark.sparkContext<br>broadcast_obj = Tracker(&quot;Broadcast&quot;, payload_size_mb=100)<br>bc = sc.broadcast(broadcast_obj)<br><br>...<br><br>def task(partition_idx, iterator):<br><br>    before = rss_mb()<br>    obj = bc.value<br>    obj.counter += 1<br>    after = rss_mb()<br><br>    list(iterator)<br><br>    return [<br>        {<br>          ...<br>        }<br>    ]<br><br><br>result = rdd.mapPartitionsWithIndex(task).collect()</pre><p>결과는 명확한 차이를 보였습니다. 동일한 PID(Worker)를 기준으로, 브로드캐스트 변수가 <strong>최초 로드될 때만 1번 메모리(RSS)가 증가</strong>하고, 이후 다른 파티션을 처리할 때는 메모리 증가가 0이었습니다. Object ID가 동일하게 유지되며 Counter 값이 누적되는 것을 통해, 객체가 메모리에 캐싱되어 완벽하게 재사용됨을 알 수 있습니다.</p><pre># Broadcast Result<br>================================================================================<br>RESULT<br>================================================================================<br>{&#39;partition&#39;: 0, &#39;pid&#39;: 9108, &#39;object_id&#39;: 4566676736, &#39;counter&#39;: 1, &#39;rss_before&#39;: 30.640625, &#39;rss_after&#39;: 133.984375, &#39;rss_delta&#39;: 103.34375}<br>{&#39;partition&#39;: 1, &#39;pid&#39;: 9109, &#39;object_id&#39;: 4565405856, &#39;counter&#39;: 1, &#39;rss_before&#39;: 30.8125, &#39;rss_after&#39;: 134.171875, &#39;rss_delta&#39;: 103.359375}<br>{&#39;partition&#39;: 2, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 1, &#39;rss_before&#39;: 30.90625, &#39;rss_after&#39;: 134.359375, &#39;rss_delta&#39;: 103.453125}<br>{&#39;partition&#39;: 3, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 1, &#39;rss_before&#39;: 30.8125, &#39;rss_after&#39;: 134.28125, &#39;rss_delta&#39;: 103.46875}<br>{&#39;partition&#39;: 4, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 2, &#39;rss_before&#39;: 172.515625, &#39;rss_after&#39;: 172.515625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 5, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 2, &#39;rss_before&#39;: 172.59375, &#39;rss_after&#39;: 172.59375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 6, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 3, &#39;rss_before&#39;: 173.09375, &#39;rss_after&#39;: 173.09375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 7, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 3, &#39;rss_before&#39;: 173.0625, &#39;rss_after&#39;: 173.0625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 8, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 4, &#39;rss_before&#39;: 173.171875, &#39;rss_after&#39;: 173.171875, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 9, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 4, &#39;rss_before&#39;: 173.109375, &#39;rss_after&#39;: 173.109375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 10, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 5, &#39;rss_before&#39;: 173.234375, &#39;rss_after&#39;: 173.234375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 11, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 5, &#39;rss_before&#39;: 173.1875, &#39;rss_after&#39;: 173.1875, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 12, &#39;pid&#39;: 9109, &#39;object_id&#39;: 4565405856, &#39;counter&#39;: 2, &#39;rss_before&#39;: 172.546875, &#39;rss_after&#39;: 172.546875, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 13, &#39;pid&#39;: 9108, &#39;object_id&#39;: 4566676736, &#39;counter&#39;: 2, &#39;rss_before&#39;: 172.40625, &#39;rss_after&#39;: 172.40625, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 14, &#39;pid&#39;: 9107, &#39;object_id&#39;: 4565564832, &#39;counter&#39;: 6, &#39;rss_before&#39;: 173.234375, &#39;rss_after&#39;: 173.234375, &#39;rss_delta&#39;: 0.0}<br>{&#39;partition&#39;: 15, &#39;pid&#39;: 9106, &#39;object_id&#39;: 4554549072, &#39;counter&#39;: 6, &#39;rss_before&#39;: 173.1875, &#39;rss_after&#39;: 173.1875, &#39;rss_delta&#39;: 0.0}</pre><p>PySpark 내부적으로 .value가 최초 호출될 때 로컬 디스크의 브로드캐스트 파일을 읽어 역직렬화한 뒤, 이를 워커의 전역 컨텍스트(_broadcastRegistry)에 저장해두기 때문입니다. 클로저 방식처럼 <strong>매 파티션마다 객체를 재생성하는 비효율</strong>은 완벽히 제거되었습니다. 하지만 초기에 예상했던 <strong>파이썬 워커 수(코어 수)만큼 메모리에 중복 복제</strong>되는 한계를 확인할 수 있었습니다.</p><p><em>파이썬 워커를 재사용하지 않으면(</em><em>“spark.python.worker.reuse”, “false”),<br>클로저 변수와 동일(</em><em>counter: 1)하게 동작합니다.</em></p><h3>가설 검증 3: 대규모 데이터의 정답, Broadcast Hash Join (BHJ)</h3><p>마지막으로, Python 객체로 넘기는 대신 딕셔너리를 DataFrame으로 만들어 Spark SQL 엔진에서 Broadcast Hash Join을 수행하는 경우를 확인했습니다.</p><p><em>이 경우 아예 데이터가 파이썬 워커의 메모리 공간으로 넘어가지 않습니다.<br>Spark의 물리적 실행 엔진(Tungsten)이 JVM 내에서 자체적인 메모리 포맷(</em><em>UnsafeRow)을 활용하여 조인을 처리합니다.</em></p><h4>Executor Heap Histogram 분석 결과:</h4><pre># Executor Heap Histogram<br># Rank | Instances | Bytes | Class Name<br><br>1882 | 1 | 24 | org.apache.spark.sql.execution.joins.LongHashedRelation</pre><p>결과가 보여주듯, 각 Executor의 JVM 힙 메모리 공간에 LongHashedRelation 객체가 <strong>단 1개만</strong> 인스턴스화되어 모든 Core(Task)가 이를 공유합니다.<br>Python과 JVM 사이의 직렬화/역직렬화 통신 비용이 전혀 발생하지 않으며, 코어 수만큼 데이터가 복제되지도 않는 가장 이상적인 상태입니다.</p><h3>결론 및 요약</h3><p>위의 로깅과 코드 분석을 바탕으로, PySpark 환경에서 참조해야 할 메타데이터를 전달하는 아키텍처 전략을 다음과 같이 정리할 수 있습니다.</p><p>이를 통해서 Column/Row 형태의 데이터나 큰 데이터를 전송하는 상황에서 단순히 <strong>Broadcast Variable로 전달하는 것이 아닌</strong> 상황에 따라 <strong>Broadcast Hash Join으로 처리</strong>하는 것도 고려해보면 좋을 거 같습니다.</p><h4>Closure Variable</h4><ul><li><strong>네트워크 전송:</strong> JVM까지는 Broadcast로 1회 전송</li><li><strong>파이썬 메모리 적재:</strong> 매 Task(파티션)마다 새롭게 Unpickle</li><li><strong>단점: </strong>처리 파티션 수만큼 객체 생성/파괴 반복 (극심한 GC 발생)</li></ul><h4>Broadcast Variable</h4><ul><li><strong>네트워크 전송:</strong> JVM까지 Broadcast 1회 전송</li><li><strong>파이썬 메모리 적재:</strong> Worker Process(PID)당 최초 1회 적재</li><li><strong>단점:</strong> Core 수(Worker 수)만큼 메모리에 데이터 복제됨</li></ul><h4>Broadcast Hash Join</h4><ul><li><strong>네트워크 전송:</strong> JVM까지 Broadcast 1회 전송</li><li><strong>파이썬 메모리 적재:</strong> Python Worker로 데이터 전송 안 됨</li><li><strong>단점:</strong> 테이블로 관리 시 네트워크 I/O 발생, 동적 생성 시 Driver 부담 발생</li></ul><h3>참조</h3><ul><li><strong>DAGScheduler의 Task Broadcast 로직:</strong><br>드라이버의 네트워크 병목을 방지하기 위해 submitMissingTasks 내부에서 직렬화된 Task Binary 객체를 한 번만 브로드캐스팅하는 최적화 로직</li></ul><p><a href="https://github.com/apache/spark/blob/master/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala">spark/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala at master · apache/spark</a></p><ul><li><strong>pyspark.daemon 프로세스 포크 (Process Fork):<br></strong>JVM Executor의 요청을 받아 리눅스의 os.fork()를 통해 실제 파이썬 워커 프로세스를 생성해 내는 백그라운드 데몬의 동작을 확인</li></ul><p><a href="https://github.com/apache/spark/blob/master/python/pyspark/daemon.py">spark/python/pyspark/daemon.py at master · apache/spark</a></p><ul><li><strong>Python Worker의 역직렬화(Unpickle):<br></strong>파이썬 워커가 JVM으로부터 Task를 전달받을 때마다 read_command 함수 등에서 바이트 배열을 파이썬 객체로 역직렬화(cloudpickle 등 활용)하여 메모리에 적재</li></ul><p><a href="https://github.com/apache/spark/blob/master/python/pyspark/worker.py">spark/python/pyspark/worker.py at master · apache/spark</a></p><ul><li><strong>Broadcast Hash Join의 LongHashedRelation:<br></strong>JVM 내의 Tungsten 엔진에서 조인을 처리하기 위해 단 1개만 생성하여 재사용하는 해시 테이블 구조체</li></ul><p><a href="https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/HashedRelation.scala">spark/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/HashedRelation.scala at master · apache/spark</a></p><h3>전체 코드</h3><ul><li>tracker.py</li></ul><pre>import os<br>import pickle<br>import socket<br><br><br>class Tracker:<br>    serialize_count = 0<br><br>    def __init__(self, mode_name, payload_size_mb=100):<br><br>        self.mode_name = mode_name<br><br>        self.counter = 0<br><br>        self.payload = b&quot;x&quot; * payload_size_mb * 1024 * 1024<br><br>        print(<br>            f&quot;&quot;&quot;<br>            CREATE<br>            mode={mode_name}<br>            pid={os.getpid()}<br>            host={socket.gethostname()}<br>            obj_id={id(self)}<br>            &quot;&quot;&quot;<br>        )<br><br>    def __getstate__(self):<br><br>        Tracker.serialize_count += 1<br><br>        size_mb = len(pickle.dumps(self.__dict__)) / 1024 / 1024<br><br>        print(<br>            f&quot;&quot;&quot;<br>            SERIALIZE<br>            mode={self.mode_name}<br>            serialize_idx={Tracker.serialize_count}<br>            pid={os.getpid()}<br>            host={socket.gethostname()}<br>            obj_id={id(self)}<br>            size={size_mb:.2f}MB<br>            &quot;&quot;&quot;<br>        )<br><br>        return self.__dict__</pre><ul><li>test_closure.py</li></ul><pre>import os<br>import socket<br><br>import psutil<br>from tracker import Tracker<br><br>from pyspark.sql import SparkSession<br><br><br>def rss_mb():<br>    return psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024<br><br><br>spark = (<br>    SparkSession.builder.master(&quot;local-cluster[2,2,1024]&quot;)<br>    .appName(&quot;ClosureTest&quot;)<br>    .config(&quot;spark.python.worker.reuse&quot;, &quot;true&quot;)<br>    .getOrCreate()<br>)<br><br>sc = spark.sparkContext<br>sc.setLogLevel(&quot;DEBUG&quot;)<br><br>sc.addPyFile(&quot;tracker.py&quot;)<br><br>print(<br>    f&quot;&quot;&quot;<br>    DRIVER<br>    pid={os.getpid()}<br>    host={socket.gethostname()}<br>    &quot;&quot;&quot;<br>)<br><br>closure_obj = Tracker(&quot;Closure&quot;, payload_size_mb=1)<br><br>rdd = sc.parallelize(range(16), 16)<br><br><br>def task(partition_idx, iterator):<br><br>    before = rss_mb()<br><br>    obj = closure_obj<br><br>    obj.counter += 1<br><br>    after = rss_mb()<br><br>    list(iterator)<br><br>    return [<br>        {<br>            &quot;partition&quot;: partition_idx,<br>            &quot;pid&quot;: os.getpid(),<br>            &quot;host&quot;: socket.gethostname(),<br>            &quot;object_id&quot;: id(obj),<br>            &quot;counter&quot;: obj.counter,<br>            &quot;rss_before&quot;: before,<br>            &quot;rss_after&quot;: after,<br>            &quot;rss_delta&quot;: after - before,<br>        }<br>    ]<br><br><br>result = rdd.mapPartitionsWithIndex(task).collect()<br><br>print(&quot;\n&quot;)<br>print(&quot;=&quot; * 80)<br>print(&quot;RESULT&quot;)<br>print(&quot;=&quot; * 80)<br><br>for row in sorted(result, key=lambda x: x[&quot;partition&quot;]):<br>    print(row)<br><br>spark.stop()</pre><ul><li>test_broadcast.py</li></ul><pre>import os<br>import socket<br><br>import psutil<br>from tracker import Tracker<br><br>from pyspark.sql import SparkSession<br><br><br>def rss_mb():<br>    return psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024<br><br><br>spark = (<br>    SparkSession.builder.master(&quot;local-cluster[2,2,1024]&quot;)<br>    .appName(&quot;ClosureTest&quot;)<br>    .config(&quot;spark.python.worker.reuse&quot;, &quot;true&quot;)<br>    .getOrCreate()<br>)<br><br>sc = spark.sparkContext<br>sc.setLogLevel(&quot;DEBUG&quot;)<br><br>sc.addPyFile(&quot;tracker.py&quot;)<br><br>print(<br>    f&quot;&quot;&quot;<br>    DRIVER<br>    pid={os.getpid()}<br>    host={socket.gethostname()}<br>    &quot;&quot;&quot;<br>)<br><br>closure_obj = Tracker(&quot;Closure&quot;, payload_size_mb=1)<br><br>rdd = sc.parallelize(range(16), 16)<br><br><br>def task(partition_idx, iterator):<br><br>    before = rss_mb()<br><br>    obj = closure_obj<br><br>    obj.counter += 1<br><br>    after = rss_mb()<br><br>    list(iterator)<br><br>    return [<br>        {<br>            &quot;partition&quot;: partition_idx,<br>            &quot;pid&quot;: os.getpid(),<br>            &quot;host&quot;: socket.gethostname(),<br>            &quot;object_id&quot;: id(obj),<br>            &quot;counter&quot;: obj.counter,<br>            &quot;rss_before&quot;: before,<br>            &quot;rss_after&quot;: after,<br>            &quot;rss_delta&quot;: after - before,<br>        }<br>    ]<br><br><br>result = rdd.mapPartitionsWithIndex(task).collect()<br><br>print(&quot;\n&quot;)<br>print(&quot;=&quot; * 80)<br>print(&quot;RESULT&quot;)<br>print(&quot;=&quot; * 80)<br><br>for row in sorted(result, key=lambda x: x[&quot;partition&quot;]):<br>    print(row)<br><br>spark.stop()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78bd682f67c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part2: Spark on Kubernetes 인프라 구축 및 도입 여정]]></title>
            <link>https://medium.com/@seonggil/part2-spark-on-kubernetes-%EC%9D%B8%ED%94%84%EB%9D%BC-%EA%B5%AC%EC%B6%95-%EB%B0%8F-%EB%8F%84%EC%9E%85-%EC%97%AC%EC%A0%95-a48c9c4ed4db?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/a48c9c4ed4db</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Sun, 17 May 2026 06:46:37 GMT</pubDate>
            <atom:updated>2026-05-17T07:06:13.060Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>최근 Apache Airflow와 Apache Spark을 활용해서 <a href="https://www.gharchive.org/">GH Archive</a> 데이터를 활용한 프로젝트를 진행했습니다.<br>해당 프로젝트를 진행하면서 마주친 문제들에 대해 정리한 글 입니다.</blockquote><ul><li><a href="https://medium.com/@seonggil/part1-airflow-spark-%EA%B8%B0%EB%B0%98%EC%9D%98-data-pipeline-architecture-%EC%84%A4%EA%B3%84-%EB%B0%8F-%EA%B0%9C%EB%B0%9C-%ED%99%98%EA%B2%BD-%EA%B5%AC%EC%B6%95-e381078adf20">Part1: Airflow, Spark 기반의 Data pipeline Architecture 설계 및 개발 환경 구축</a></li><li><a href="https://medium.com/@seonggil/part2-spark-on-kubernetes-%EC%9D%B8%ED%94%84%EB%9D%BC-%EA%B5%AC%EC%B6%95-%EB%B0%8F-%EB%8F%84%EC%9E%85-%EC%97%AC%EC%A0%95-a48c9c4ed4db"><strong>Part2: Spark on Kubernetes 인프라 구축 및 도입 여정</strong></a></li></ul><p><a href="https://github.com/gitsight-app/gitsight-data-pipeline">GitHub - gitsight-app/gitsight-data-pipeline</a></p><h3>Introduction</h3><p>Gitsight 프로젝트를 진행하면서 매일 Airflow를 통해 Apache Spark Job을 실행하며, 깃허브에서 발생하는 데이터를 수집하여 OLTP(Supabase)까지 가공, 처리, 적재(ETL)하는 데이터 파이프라인을 구축했습니다.</p><p>시간단위로 들어오는 <a href="https://www.gharchive.org/">원천 데이터(</a><a href="https://www.gharchive.org/"><em>2026–05–08–04.json.gz, 2026–05–08–05.json.gz</em>)</a> 특성과 파이프라인의 추가에 따라 시간의 정각(HH:00)에 실행되는 병목이 증가했고, 이에 따라 더 효율적이고 빠른 배치 컴퓨팅 환경을 구축할 필요성도 높아졌습니다.</p><p>이 글에서는 On-Premise(with EC2, Docker) 기반의 Spark, Airflow 운영 환경을 Spark on Kubernetes 환경으로 마이그레이션하는 과정에서 겪은 경험과 이슈를 공유하겠습니다.</p><h3>기존 인프라 훑어보기</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEQdLjHs59c_Fe9t73hXZg.png" /><figcaption>Docker 기반의 Spark Cluster 및 Airflow</figcaption></figure><p>Spark Cluster는 Spark Standalone모드로 배포되며,<br>Airflow의 SparkSubmitOperator 를 사용하여 Spark Job을 실행(submit)합니다.</p><p>Spark Job 또는 Airflow Task의 실패(OOM)가 Airflow 전체 서비스의 중단에 영향을 주지 않도록 Airflow Worker를 분리된 환경에서 실행시켰으며, <strong>단일화된 로그 관리</strong>와 <strong>코드(JAR, Python) 배포의 편의성</strong>을 위해 Airflow Worker를 Driver(Client Mode)로 사용하였습니다.</p><h3>문제 정의: 오토스케일 부재</h3><p>데이터 파이프라인의 증가로 곂치는 시간대에 여러 Spark Applications이 동시에 실행되며 병목 현상이 발생했습니다.</p><p>고정된 인스턴스(Spark Master, Spark Worker)를 기반으로 파이프라인이 운영됨에 따라 여러 병목현상과 리소스 낭비가 발생했습니다.</p><p>원천 시스템의 데이터는 매 시간단위로 적재됩니다.<br>원천 데이터가 raw/ 에 정상적으로 적재되면 메달리온 아키텍처 기반의 Data Lakehouse(S3, Iceberg)를 기반으로 데이터를 변환 및 적재(ELT/ETL)하여<br>데이터의 구조와 품질을 점진적으로 개선하고 최종적으로 OLTP(Supabase)환경에 서빙됩니다.</p><p>이 과정에서 데이터 파이프라인의 원천 데이터를 빠르게 변환 및 제공하기 위해,<br><strong>HH:00 ~ HH:20</strong> 사이에 많은 Spark Job이 실행됩니다.<br>그 결과 00~20분 사이에는 많은 Spark Job이 한 번에 실행되며 다른 작업에 의한 병목이, 다른 시간대에는 Spark Worker의 불필요한 리소스 점유가 발생했습니다.</p><h3>문제 정의2: 멀티 호스트 컨테이너 간 네트워크 통신 및 관리 복잡성</h3><p>Spark Standalone 클러스터를 멀티 호스트(다중 서버) Docker 환경으로 구성함에 따라, 컨테이너 간 격리로 인한 네트워크 통신 실패와 복잡한 인프라 관리 오버헤드가 발생했습니다</p><p>Spark의 Driver와 Executor는 내부적으로 양방향 통신(Block Manager, Heartbeat 등)이 필수적으로 발생합니다.<br>이때 Driver가 자신의 내부 가상 IP를 Executor에게 전달하게 되면서 Connection Refused 및 타임아웃 에러가 발생했으며, 이를 해결하기 위해 Airflow Connections을 통해 Driver의 정보(host, block)주입하거나, 각 Spark Worker, Master의 경우 배포되는 서버에 따라 알맞은 env설정(SPARK_MASTER_URL)이 필요했습니다.</p><pre># Airflow Spark Connections Extra<br>{<br>  &quot;spark.driver.bindAddress&quot;: &quot;0.0.0.0&quot;,<br>  &quot;spark.driver.host&quot;: &quot;10.0.0.68&quot;,<br>  &quot;spark.driver.port&quot;: &quot;7087&quot;,<br>  &quot;spark.blockManager.port&quot;: &quot;7088&quot;,<br>  &quot;spark.port.maxRetries&quot;: &quot;10&quot;<br>}</pre><p>이로 인해서 Spark 및 Airflow를 배포할 때 복잡성이 증가했고, 각 인스턴스에 종속되는 문제가 발생했습니다.</p><h3>Spark on Kubernetes Preview</h3><p>최종적으로 k3s기반의 Spark, Airflow 및 Catalog 및 S3와 같은 인스턴스를 모두 이관하여 위 목표들을 모두 달성할 수 있었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uT2zYEHl5fVGpNnj621xrQ.png" /></figure><ol><li>Airflow는 SparkKubernetesOperator 통해서 Spark Application을 spark-applications 네임스페이스에 배포합니다</li><li>Spark Operator는 spark-applications에 요청된 작업 목록을 감시하고 있다가 <br>요청된 spec에 따라 Driver, Executor를 생성하고 Job을 실행합니다.</li></ol><h3>Spark on Kubernetes로의 이관 시작</h3><p>기존의 docker-compose 기반의 환경에서 Kubernetes환경을 사용하기 위해서는 몇 가지 사전 작업이 필요했습니다.</p><ol><li>기존 Docker Volume을 통해 배포, 동기화되던 Spark, Airflow Code의 배포 전략</li><li>단일 진실 공급원(Single Source Of Truth)기반의 인프라 환경 관리 및 상태 확인</li></ol><h3>코드, 이미지 배포 및 동기화를 위한 CI/CD Workflow 설계</h3><p>가장 먼저 기존에 Docker Volume을 통해 간단하게 코드를 동기화하고<br>docker compose up --build 를 통해 Spark, Airflow 이미지를 최신화 하던 CI 워크플로우를 수정해야했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8s6u30Wbunf3DklvmLqTQ.png" /><figcaption><strong>CI/CD Workflow</strong></figcaption></figure><p>Spark, Airflow의 이미지 크기는 각각 약 <strong>1.6GB ,805 MB</strong>정도 되었기 때문에, Network I/O를 고려하여 GitHub Actions에서는 조건(<em>Create PR, Merge PR</em>)에 맞는 k8s Job을 트리깅하도록 만든 후 클러스터 내부에서 이미지 빌드 및 푸쉬하는 Pod를 실행하도록 구현하였습니다.</p><p>Latest Tag를 사용할 경우 ArgoCD가 변경을 감지하지 못하거나, 배포 추적이 어려워지기 때문에 commit hash기반의 이미지 Tagging 전략이 필요합니다.</p><p>Airflow에서 Spark Job을 배포할 때 최신 이미지를 사용할 수 있도록<br>이미지 배포 후 Airflow Helm Chart의 Value를github-bot 을 통해서 수정하는 로직도 함께 추가했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*1LHhX5nhF4O3LxFHH9q7Fg.png" /><figcaption><a href="https://github.com/gitsight-app/gitsight-data-pipeline/pull/34/changes/cc28ba1e5cec302d791214ed17eb6cfb692ef059#diff-0171a2845f103afc4255c0bc39ee1c35b16d12fa3cf82f90affb1f215ec102b5R32-L35">github-bot commit</a></figcaption></figure><p>이로 인해 Spark Job 실패 시 같은 환경에서의 에러 상황 재현하고 쉽게 추적할 수 있었습니다.</p><h3>트러블슈팅: Kubernetes RBAC</h3><p>다음과 같은 구조로 Spark Job의 생명주기가 동작하게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*mBJPtrjD_MbhBbMyk8nQXg.png" /><figcaption><strong>Spark Job Lifecycle</strong></figcaption></figure><ol><li><strong>Airflow의 작업 제출 (Submit)</strong><br>Airflow Worker가 SparkKubernetesOperator를 통해 실행할 Spark 작업 정의서(SparkApplication 이라는 Custom Resource 자원)를 YAML 형태로 작성하여 k8s API 서버에 제출합니다</li><li><strong>Spark Operator의 감지 및 Driver 생성 (Reconcile)</strong><br>k8s 클러스터에 상주하며 감시하던 <strong>Spark Operator</strong>가 새로운 SparkApplication 자원이 생성된 것을 감지합니다.<br>Operator는 이 명세서를 해석하여 실제 작업을 총괄할 <strong>Spark Driver Pod</strong>을 클러스터에 띄웁니다.</li><li><strong>Spark Driver의 획득 및 Executor 생성 (Orchestrate)<br></strong>구동된 <strong>Spark Driver Pod</strong> 내부의 Spark 컨텍스트가 k8s API 서버에 직접 요청을 날려, 실제 데이터를 나누어 처리할 <strong>Spark Executor Pod</strong>들을 필요한 개수만큼 동적으로 생성합니다.</li><li><strong>작업 실행 (Execute)<br></strong>생성된 Executor Pod들이 분산 작업을 수행하고 결과를 Driver에게 보고합니다. 작업이 끝나면 Executor Pod들은 자동으로 삭제됩니다</li><li><strong>모니터링 및 완료 (Monitor)</strong><br>Airflow는 SparkKubernetesSensor를 통해 SparkApplication의 상태를 주기적으로 추적합니다. Driver가 최종 성공/실패를 기록하면 Airflow가 이 상태를 받아와 DAG 태스크를 완료 처리합니다.</li></ol><p>위와 같은 플로우가 유기적으로 동작하기 위해서는 k8s의 RBAC를 설정해줘야합니다.</p><ul><li>Airflow는 k8s API에 SparkApplication이라는 커스텀 자원(CRD)을 생성, 조회, 삭제할 수 있어야 합니다.</li><li><strong>Spark Driver</strong>는 스스로 쿠버네티스 API에 접근하여 Executor Pod들을 직접 만들고 지워야 하므로, Pod 제어 권한이 반드시 필요합니다</li></ul><p><em>Spark Operator의 경우 Helm 차트로 설치 시 자동으로 권한을 생성합니다.</em></p><p>더불어 spark job을 위한 application을 생성 시 사전에 정의한 Service Account(SA)를 할당해줘야 합니다.</p><pre>...<br><br>  driver:<br>    image: &quot;{{ var.value.SPARK_IMAGE }}&quot;<br>    imagePullPolicy: IfNotPresent<br>    cores: 1<br>    coreRequest: &quot;100m&quot;<br>    memory: &quot;512m&quot;<br>    serviceAccount: airflow-spark<br>    labels:<br>      version: &quot;3.5.1&quot;<br><br>...</pre><h3>안전한 마이그레이션을 위한 검증 장치</h3><p>데이터 파이프라인 인프라와 코드를 전역으로 수정하기에 앞서,<br><strong><em>“마이그레이션 후 이전 파이프라인과 동일한 동작을 보장하는가”</em></strong>에 대해 고민했습니다.</p><p>다음과 같은 2개의 요구사항이 있었습니다.</p><ol><li>정량적인 지표를 기반하여 해당 데이터의 정합성을 검증하기</li><li>만약 데이터의 정합성이 깨졌을 경우 프로덕션 또는 다운스트림(Downstream)에 데이터의 오염이 전파되지 않도록 막기</li></ol><p>두 요구사항을 충족하기 위해 <a href="https://greatexpectations.io/">great expectations</a>을 활용한<br><a href="https://swalloow.github.io/write-audit-publish/">WAP(Write-Audit-Publish) 패턴</a>을 파이프라인 전역에 적용했습니다.</p><p><strong>great expectations</strong>의 경우 해당 데이터(테이블)이 가져야하는 비즈니스 요구사항을 코드로 관리하여 변경을 추적하고 S3의 정적 리소스로 빌드를 통해 데이터 퀄리티 검증을 모니터링할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGNM6_cUAHb8-JAc4-zAgA.png" /><figcaption><strong>ETL/ELT Pipeline</strong></figcaption></figure><ol><li>Nessie Catalog의 브랜치 기능을 기반으로 완벽히 격리된 환경을 구축합니다.</li><li>기존 ETL/ELT 로직을 수행하여 데이터를 변환 적재합니다.</li><li>great expecations로 정의한 데이터 검증 로직을 해당 Batch에 들어온 데이터를 대상으로 검증합니다.</li><li>검증이 성공한다면 Nessie Catalog의 브랜치를 main에 머지하여 다운스트림과 프로덕션 환경에서 읽을 수 있도록 구성합니다.</li></ol><p>이와 같은 Nessie 기반의 WAP 검증 프로세스를 통해, Kubernetes 인프라 마이그레이션 전후로 파이프라인의 동일 동작성을 입증하고 데이터 적재 시 발생할 수 있는 정합성 변형 유무를 안전하게 검증할 수 있었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQn039hIMdxXhO2wSu1wyQ.png" /><figcaption><strong>Great Expectations Data Docs</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a48c9c4ed4db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Great Expectations(GX): to check your data quality]]></title>
            <link>https://levelup.gitconnected.com/great-expectations-gx-to-check-your-data-quality-2bd3465268e2?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bd3465268e2</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[great-expectations]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[data-quality]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 20:15:57 GMT</pubDate>
            <atom:updated>2026-05-18T14:36:22.294Z</atom:updated>
            <content:encoded><![CDATA[<h3>Verifying Data Quality with Great Expectations (GX)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZo6O8m7wKDZTuFpbUpPrg.png" /><figcaption><strong>Great Expectations</strong></figcaption></figure><p><strong>Data Quality Check</strong>, in its simplest terms, is the process of verifying a fundamental question: <strong>“Is our data reliable and fit for use?”</strong></p><p>No matter how sophisticated your dashboards or how advanced your machine learning models are, the output becomes worthless if the underlying data is riddled with gaps or inconsistent formats. This is the classic “Garbage In, Garbage Out” problem. However, ensuring this integrity at the scale of Big Data is a significant challenge, especially when it comes to visual verification.</p><h3>1. The 6 Core Dimensions of Data Quality</h3><blockquote>When we say data is “high quality,” we typically evaluate it based on these six foundational pillars:</blockquote><ol><li><strong>Accuracy:<br><em>Question:</em></strong><em> Does the data reflect real-world facts?<br></em><strong><em>Example:</em></strong><em> Is a customer’s age recorded as 200?</em></li><li><strong>Completeness<br><em>Question:</em></strong><em> Is all the required data present without missing values?<br></em><strong><em>Example:</em></strong><em> Is the percentage of “Null” values within an acceptable threshold?</em></li><li><strong>Consistency:<br><em>Question:</em></strong><em> Is the information uniform across different systems or tables?</em><strong><em>Example:</em></strong><em> Does an “Order Completed” status in the sales table appear as “Payment Canceled” in the accounting table?</em></li><li><strong>Validity:<br><em>Question:</em></strong><em> Does the data adhere to defined formats or business rules?</em><strong><em>Example:</em></strong><em> Does an email address include an “@” symbol, or is the date formatted as </em><em>YYYY-MM-DD?</em></li><li><strong>Timeliness:<br><em>Question:</em></strong><em> Is the data up-to-date and available when needed?<br></em><strong><em>Example:</em></strong><em> Does today’s dashboard accurately reflect the transactions that occurred yesterday?</em></li><li><strong>Uniqueness:<br><em>Question:</em></strong><em> Are there any redundant or duplicate records?<br></em><strong><em>Example:</em></strong><em> Was the same transaction ID generated twice for a single purchase?</em></li></ol><h3>2. Why Data Quality Matters?</h3><blockquote>Beyond simply <strong>“keeping data clean,” </strong>ensuring data quality is critical for several key business reasons:</blockquote><ul><li><strong>Increased Trust in Decision-Making</strong> Inaccurate data leads to flawed strategic decisions by leadership. Data quality checks serve as a <strong>“seal of assurance”</strong> for the metrics and insights delivered by the data team, ensuring that every stakeholder can rely on the numbers.</li><li><strong>Cost Efficiency (Shift-Left Approach)</strong> Fixing data errors becomes exponentially more expensive and resource-intensive the further they travel <strong>downstream</strong>. By implementing proactive checks early in the pipeline, you can prevent costly “data disasters” before they impact end-users.</li><li><strong>Scalable Pipeline Governance</strong> As data volume grows, manual verification becomes impossible. Leveraging tools like <strong>Great Expectations (GX)</strong> allows you to automate the validation process, enabling the system to autonomously detect and flag anomalies without human intervention.</li></ul><h3>3. Where to Implement Data Quality Checks</h3><blockquote>Data quality isn’t a one-time event; it should be verified at multiple touchpoints as data flows through the pipeline.</blockquote><ul><li><strong>Ingestion (Entry Stage)</strong> Validate the data the moment it is brought in from the source. At this stage, the primary focus is often <strong>schema validation</strong> — ensuring that data types are correct and the structure matches expectations.</li><li><strong>Transformation (Processing Stage)</strong> As you clean and aggregate data, you must verify the <strong>business logic</strong>. For example, you might check if the sum of individual transactions matches the total recorded value or if any calculated fields fall within a logical range.</li><li><strong>Serving (Delivery Stage)</strong> This is the final checkpoint before data reaches the end-user or a BI tool. Here, you verify the <strong>integrity of the final output</strong> to ensure that the processed data is consistent, complete, and ready for decision-making.</li></ul><p><em>To automate these checkpoints and manage them as code (Validation-as-Code), </em><strong><em>Great Expectations (GX)</em></strong><em> has emerged as one of the most powerful and popular tools in the modern data stack.</em></p><h3>Core Components of Great Expectations (GX)</h3><blockquote>To effectively manage data quality, GX is built upon several key components that work together seamlessly:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gw0AoOFwqGb5IApYA8arOQ.png" /><figcaption><strong>Components of Great Expectations</strong></figcaption></figure><h4>Data Context</h4><blockquote>The <strong>Data Context</strong> is the “central control tower” of a GX project.</blockquote><p>It manages all project configurations, including settings files, datasource information, and Expectation Suites. It typically exists as a YAML file within the gx/ directory or as a Python object, defining where the data is located and where the results should be stored. You can configure the storage path to cloud services like Amazon S3, which allows validation results to be delivered directly as Data Docs reports.</p><h4>Datasource</h4><blockquote>The <strong>Datasource</strong> defines which data GX will access</blockquote><p>It handles connections to databases (PostgreSQL, BigQuery), cloud storage (S3, GCS), or local files (CSV, Parquet). Beyond simply specifying a path, it also determines the execution engine — such as Pandas, Spark, or SQLAlchemy — that will be used to process the data.</p><h4>Expectations &amp; Expectation Suite</h4><blockquote>These are the heart of GX and represent the actual validation rules</blockquote><ul><li><strong>Expectation:<br></strong>A granular “unit rule” defining a specific requirement for your data. You can find a comprehensive list in the <a href="https://greatexpectations.io/expectations/">GX Expectations Gallery</a>.</li><li><strong>Expectation Suite:<br></strong>A collection of Expectations bundled into a single test scenario. For example, a “User Profile Validation Suite” might include rules ensuring that IDs are unique and email addresses follow a valid format.</li></ul><p><em>For example, a “User Information Table Validation Suite” would include rules such as unique IDs and email format compliance.</em></p><h4>Batch Request</h4><blockquote>A <strong>Batch Request</strong> defines exactly “which” data should be retrieved from a Datasource for validation.</blockquote><p>It specifies the subset of data (a “Batch”) to be processed, such as a specific database table, a file from a directory, or a filtered slice of data (e.g., records from a specific date). Essentially, it acts as the bridge that selects the target data from the Datasource to be handed over to the validation engine.</p><h4>Checkpoint</h4><blockquote>The unit of execution that applies defined rules (Expectation Suites) to actual data (Datasources) to perform validation</blockquote><p>It defines: “Which data should be inspected with which rules, and what actions (such as sending alerts) should be taken once the results are generated?”</p><h3>Example: Validating User Data</h3><blockquote>Let’s explore the lifecycle of a data validation process using Great Expectations.</blockquote><pre># users.csv<br><br>user_id,user_name,email,age,signup_date,status<br>1,Seonggil,seonggil@example.com,28,2024-01-15,active<br>2,James,james@test.com,34,2024-02-10,active<br>3,Anna,anna_google.com,22,2024-03-05,pending<br>4,,secret@hidden.com,-5,2024-03-20,active<br>5,Chris,chris@example.com,150,2024-04-01,canceled<br>1,Duplicate,double@test.com,30,2024-04-10,active<br>6,Olivia,olivia@example.com,25,2025-12-31,unknown</pre><ul><li><strong>Identified Issues:<br>-</strong> Duplicate user IDs: (user_id: 1)<br><strong>-</strong> Invalid email format: (user_id: 3, email: anna_google.com)</li></ul><pre>pip install &quot;great-expectations&gt;=0.18.22,&lt;1.0.0&quot;</pre><p><strong><em>Note:</em></strong><em> Syntax may differ in version </em><em>1.x.x or later.</em></p><h4>Create Or Get Context</h4><blockquote>The <strong>Data Context</strong> manages execution results and test scenarios (checkpoints, expectations, validations) in JSON format. These can be reused based on their assigned names.</blockquote><pre>import great_expectations as gx<br><br>context = gx.get_context()<br># context = gx.get_context(project_config=project_config)</pre><h4>Define Datasource</h4><blockquote>A <strong>Datasource</strong> contains information regarding “where the data is coming from.”</blockquote><pre>context.add_datasource(<br>    name=&quot;sample_data&quot;,<br>    class_name=&quot;Datasource&quot;,<br>    execution_engine={<br>        &quot;class_name&quot;: &quot;PandasExecutionEngine&quot; # using Pandas<br>    },<br>    data_connectors={<br>        &quot;default_runtime_data_connector_name&quot;: {<br>            &quot;class_name&quot;: &quot;RuntimeDataConnector&quot;,<br>            &quot;batch_identifiers&quot;: [&quot;default_identifier_name&quot;],<br>        }<br>    },<br>)</pre><h4>Create Expectations &amp; Suite</h4><blockquote>You can apply specific <strong>Expectation Types</strong> to your data source. Explore the GX Expectations Gallery for more rules</blockquote><p><a href="https://greatexpectations.io/expectations/">GX Expectations Gallery</a></p><pre>from great_expectations.core import ExpectationConfiguration<br><br>suite_name = &quot;users_df_suite&quot;<br><br># Validate User Id uniqueness<br>ex1 = ExpectationConfiguration(<br>        expectation_type=&quot;expect_column_values_to_be_unique&quot;,<br>        kwargs={&quot;column&quot;: &quot;user_id&quot;},<br>      )<br><br># Validate Email format via Regex<br>email_regex = r&quot;^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$&quot;<br>ex2 = ExpectationConfiguration(<br>    expectation_type=&quot;expect_column_values_to_match_regex&quot;,<br>    kwargs={<br>        &quot;column&quot;: &quot;email&quot;,<br>        &quot;regex&quot;: email_regex<br>    },<br>)<br><br># Apply Suite to Context<br>context.add_or_update_expectation_suite(<br>    suite_name,<br>    expectations=[ex1, ex2]<br>)<br><br># Verify the suite<br>context.list_expectation_suites()<br># [ExpectationSuiteIdentifier::users_df_suite]</pre><pre>context.list_expectation_suites()<br># [ExpectationSuiteIdentifier::users_df_suite]<br><br>print(suite)<br><br># {<br>#     &quot;expectation_suite_name&quot;: &quot;users_df_suite&quot;,<br>#     &quot;ge_cloud_id&quot;: null,<br>#     &quot;expectations&quot;: [<br>#         {<br>#             &quot;expectation_type&quot;: &quot;expect_column_values_to_be_unique&quot;,<br>#             &quot;kwargs&quot;: {<br>#                 &quot;column&quot;: &quot;id&quot;<br>#             },<br>#             &quot;meta&quot;: {}<br>#         },<br>#         {<br>#             &quot;expectation_type&quot;: &quot;expect_column_values_to_match_regex&quot;,<br>#             &quot;kwargs&quot;: {<br>#                 &quot;column&quot;: &quot;email&quot;,<br>#                 &quot;regex&quot;: &quot;^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$&quot;<br>#             },<br>#             &quot;meta&quot;: {}<br>#         }<br>#     ],<br>#     &quot;data_asset_type&quot;: null,<br>#     &quot;meta&quot;: {<br>#         &quot;great_expectations_version&quot;: &quot;0.18.22&quot;<br>#     }<br># }</pre><h4>Batch Request</h4><blockquote>A <strong>Batch Request</strong> defines the unit of data to be validated</blockquote><pre>import pandas as pd<br>from great_expectations.core.batch import RuntimeBatchRequest<br><br>target_df = pd.read_csv(&quot;./data/users.csv&quot;)<br>data_asset_name = &quot;users_info_asset&quot;  # Name of the validation target<br><br>batch_request = RuntimeBatchRequest(<br>    datasource_name=&quot;sample_data&quot;,<br>    data_connector_name=&quot;default_runtime_data_connector_name&quot;,<br>    data_asset_name=data_asset_name,<br>    runtime_parameters={&quot;batch_data&quot;: target_df}, # DF loaded at runtime<br>    batch_identifiers={<br>        &quot;default_identifier_name&quot;: &quot;default_id&quot;  # Using &quot;default_id&quot; as identifier<br>    },<br>)</pre><ul><li><strong>data_asset_name:</strong> Defines “what” the data is (e.g., users)</li><li><strong>batch_identifiers:</strong> Defines the specific characteristics of the current batch (e.g., user data loaded on 2024–01–01)</li></ul><h4>Checkpoint</h4><blockquote>By defining a <strong>Checkpoint</strong>, you can group which BatchRequest to validate against which ExpectationSuite, and determine subsequent <strong>Actions</strong> (e.g., updating docs, sending alerts).</blockquote><pre>checkpoint_name = &quot;sample_checkpoint&quot;<br><br>checkpoint = context.add_or_update_checkpoint(<br>        name=checkpoint_name,<br>        validations=[ # Multiple suites can be applied<br>            {<br>                &quot;expectation_suite_name&quot;: suite_name,<br>            }<br>        ],<br>        action_list=[<br>            {<br>                &quot;name&quot;: &quot;store_validation_result&quot;,<br>                &quot;action&quot;: {&quot;class_name&quot;: &quot;StoreValidationResultAction&quot;},<br>            },<br>            {<br>                &quot;name&quot;: &quot;update_data_docs&quot;,<br>                &quot;action&quot;: {&quot;class_name&quot;: &quot;UpdateDataDocsAction&quot;},<br>            },<br>        ],<br>    )<br><br># Run Checkpoint<br>checkpoint.run(<br>    run_name=&quot;sample_checkpoint_at_2026_04_18&quot;,<br>    batch_request=batch_request,<br>)</pre><h4>Result (Data Docs)</h4><blockquote>Results are rendered in HTML, providing a user-friendly interface to review validation outcomes.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeteAO_ylVecJXklSqSBfg.png" /><figcaption><strong>users_df_suite</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4mYJ4-q9dfWG7gjVQXpVw.png" /><figcaption><strong>Validation Results</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sei-tgensxpjl_gqVx-VuQ.png" /><figcaption><strong>Validation Result Detail</strong></figcaption></figure><p>You can confirm that it accurately validates the invalid email format (anna_google.com) and the duplicate user ID (Non-Unique ID: 1) within the previously defined CSV.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bd3465268e2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/great-expectations-gx-to-check-your-data-quality-2bd3465268e2">Great Expectations(GX): to check your data quality</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part1: Airflow, Spark 기반의 Data pipeline Architecture 설계 및 개발 환경 구축]]></title>
            <link>https://medium.com/@seonggil/part1-airflow-spark-%EA%B8%B0%EB%B0%98%EC%9D%98-data-pipeline-architecture-%EC%84%A4%EA%B3%84-%EB%B0%8F-%EA%B0%9C%EB%B0%9C-%ED%99%98%EA%B2%BD-%EA%B5%AC%EC%B6%95-e381078adf20?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/e381078adf20</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 08:30:59 GMT</pubDate>
            <atom:updated>2026-05-17T06:48:23.073Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>최근 Apache Airflow와 Apache Spark을 활용해서 <a href="https://www.gharchive.org/">GH Archive</a> 데이터를 활용한 프로젝트를 진행했습니다.<br>해당 프로젝트를 진행하면서 마주친 문제들에 대해 정리한 글 입니다.</blockquote><ul><li><a href="https://medium.com/@seonggil/part1-airflow-spark-%EA%B8%B0%EB%B0%98%EC%9D%98-data-pipeline-architecture-%EC%84%A4%EA%B3%84-%EB%B0%8F-%EA%B0%9C%EB%B0%9C-%ED%99%98%EA%B2%BD-%EA%B5%AC%EC%B6%95-e381078adf20"><strong>Part1: Airflow, Spark 기반의 Data pipeline Architecture 설계 및 개발 환경 구축</strong></a></li><li><a href="https://medium.com/@seonggil/part2-spark-on-kubernetes-%EC%9D%B8%ED%94%84%EB%9D%BC-%EA%B5%AC%EC%B6%95-%EB%B0%8F-%EB%8F%84%EC%9E%85-%EC%97%AC%EC%A0%95-a48c9c4ed4db">Part2: Spark on Kubernetes 인프라 구축 및 도입 여정</a></li></ul><p><a href="https://github.com/gitsight-app/gitsight-data-pipeline">GitHub - gitsight-app/gitsight-data-pipeline</a></p><h3>Project Summary</h3><blockquote>GhArchive란 Github에서 발생하는 이벤트(Fork, Push, Watch and Create PR)를 1시간 단위로 json.gz 형태로 제공해주며 하루에 약 3,000,000개의 Events가 적재됩니다.</blockquote><p><a href="https://docs.github.com/en/rest/using-the-rest-api/github-event-types">GitHub event types - GitHub Docs</a></p><p>OLTP(up stream)에서 발생하는 이벤트를 활용하여, 최근 1시간 동안 가장 인기(Star, Fork가 많은)있는 Repository를 대시보드화하고 변화 추이를 시계열 데이터로 제공해줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g3NtGZrnqdS1mrhGySl0gA.png" /><figcaption>Dashboard Preview</figcaption></figure><h3>Software Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skWSz1ITP3JjnV2vWD8eJQ.png" /><figcaption><strong>Software Architecture</strong></figcaption></figure><h4>Data Lake &amp; Catalog</h4><blockquote><a href="https://projectnessie.org/">Nessie Catalog</a><br><a href="https://iceberg.apache.org/">Iceberg</a><br><a href="https://www.min.io/">MinIO</a></blockquote><p>File기반의 데이터를 읽고 쓸 때 단순히 Parquet를 사용하게 된다면, Schema 변경(schema evolution) 또는 ACID(Partial Write) 등을 보장 받기 위해 Table Format을 활용해야 합니다.</p><p>테이블 포맷(Table Format)으로는 Iceberg와 Delta Lake 등이 있는데<br>그 중 Iceberg와 Nessie Catalog 기반으로 Data Lake를 구축하기로 결정했습니다.</p><p>Nessie Catalog를 선택한 이유는 Branch 기반의 <a href="https://swalloow.github.io/write-audit-publish/">WAP(Write-Audit-Publish)</a> 패턴을 적용시켜 데이터 퀄리티를 체크하고 싶은 니즈(Needs)가 있었고,<br>가벼운 데이터 작업이 예상될 때 오버헤드가 큰 Spark Job을 실행시키는 것 대신에 다른 기술 스택을 유연하게 선택할 수 있도록 비교적 벤더 종속(Vendor Lock-in)이 적은 Iceberg를 선택하였습니다.</p><h4>data visualization</h4><blockquote>React, Supabase with RLS(Row Level Security, 행 수준 보안)</blockquote><p>프로젝트를 처음 기획할 때는 Apache Superset을 활용해서 대시보드를 제공하는 것도 고려했지만, React 활용에 러닝커브가 크지 않았고 (AI가 코드를 너무 잘 작성해줘서) 그보다 서버 리소스 적인 측면에서 React, Supabase를 사용하기로 결정했습니다.</p><h3>Airflow &amp; Spark 로컬 개발환경 설정</h3><blockquote>Docker(docker compose)기반으로 Airflow, Spark을 실행시켰고,<br>Storage(MinIO) 및 Catalog의 경우 로컬 환경을 사용하는 대신 프로덕션 환경에 있는 Nessie Catalog(dev Branch)를 사용했습니다.</blockquote><h4>Build Airflow Custom Image</h4><blockquote>Spark Job을 Client Mode로 실행시키게 되면, Spark Driver가 Airflow(Worker)에서 실행되기 때문에 Airflow이미지에 Spark 명령어를 처리할 수 있는 환경을 구축해야 합니다.</blockquote><blockquote>Spark를 Airflow 이미지에 설치하는 대신, pyspark를 pip(uv)로 설치하여 Driver로 활용하는 방식을 채택했습나다.</blockquote><p>String으로 의존성을 관리하는걸 개인적으로 선호하지 않아 Spark Package의 경우 build.gradle, Python(pip)의 경우 uv를 사용하여 관리 및 이미지 빌드에 활용했습니다.</p><pre>FROM gradle:8.5-jdk17 AS jar-builder<br>WORKDIR /builder<br><br>COPY build.gradle .<br>RUN gradle copyDependencies --no-daemon<br><br>FROM apache/airflow:3.1.2-python3.11<br><br>USER root<br><br>RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \<br>    --mount=type=cache,target=/var/lib/apt,sharing=locked \<br>    apt-get update &amp;&amp; \<br>    apt-get install -y --no-install-recommends openjdk-17-jre-headless procps &amp;&amp; \<br>    ln -s /usr/lib/jvm/java-17-openjdk-$(dpkg --print-architecture) /usr/lib/jvm/java-17-home<br><br>ENV JAVA_HOME=/usr/lib/jvm/java-17-home<br>ENV PATH=&quot;$JAVA_HOME/bin:$PATH&quot;<br><br>COPY --from=jar-builder --chown=airflow:0 /builder/build/deps/*.jar /opt/airflow/jars/<br><br>COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/<br><br>USER airflow<br>WORKDIR /opt/airflow<br><br>COPY --chown=airflow:0 pyproject.toml uv.lock ./<br><br>RUN --mount=type=cache,target=/home/airflow/.cache/uv \<br>    uv pip install --no-cache-dir -r pyproject.toml</pre><ol><li>gradle:8.5-jdk17 이미지 기반의 spark package를 다운합니다.</li><li>apache/airflow:3.1.2-python3.11 로 빌드된 jars를 복사하고,<br>Java, pip(uv install)을 통해 의존성을 설치합니다.</li></ol><p>위와 같이 구성하면 Local 환경 개발 환경(.venv)와 Docker(Prod)환경을 통일시켜 jupyter notebook등에서 작성, 테스트한 코드를 바로 DAG(프로덕션)로 전환할 수 있었습니다.</p><h3>Deploy Airflow &amp; Spark on EC2</h3><blockquote>역시나, 로컬환경에서 잘 동작했던 환경을 Cloud환경에 동일한 방식으로 구축했을 때 2가지의 문제가 있었습니다.</blockquote><h4>Spark Package</h4><p>초기에 Spark Job을 실행 시킬 때는 의존성 전달을 spark-submt --packages 형태로 전달했습니다.</p><p>이 후 Airflow DAG를 확인했을 때 정상적으로 동작하다가 저녁시간에만 Job이 죽는 문제를 마주쳤습니다.<br>해당 문제는 packages로 의존성을 전달했을 때 마운트되지 않은 의존성들이 job(application)단위로 새로 다운로드 되면서 디스크가 꽉차 작업이 실패하고 있었습니다.</p><p>볼륨(공유볼륨)을 마운트하는 방식과 Spark Docker Image에 jars를 같이 묶어서 배포하는 방식이 있었는데요, 분산처리 특성 상 해당 job이 어떤 executor(server)에서 실행될지 확정할 수 없기 때문에, Spark Docker Image에 묶어서 배포하는 방식으로 해결했습니다.</p><h4>Spark Block Manager &amp; Driver Port</h4><blockquote>Spark Job을 실행시켰을 때 정상적으로 submit과 spark UI에 작업 실행은 되는데 계속 Job이 끝나지 않고 무한 대기하는 현상이 발생했습니다.</blockquote><p>이 문제는 Software Architecture상 Airflow(Spark Driver)와 Worker(executor)가 다른 subnet에 존재하면서 발생한 문제였습니다.</p><p>Spark Submit Port(7077)만 열어주면 된다고 생각했지만,<br>내부적으로 Driver와 Executor는 다음과 같은 통신을 합니다.</p><ul><li><strong>Master:</strong> 어떤 CPU/Memory가 남는지 전체 리소스를 관리합니다.<br>남는 일꾼(Worker)을 골라 드라이버에게 배정해주는 역할까지만 담당합니다.</li><li><strong>Driver:</strong> 실제 Task, Code를 볼지 상세 계획을 가지고 작업(Job)을 실행합니다. Spark Master에서 자원을 할당해주면, 실제 Task에 대한 요청은 Driver가 직접 Executor에게 요청합니다</li><li><strong>Executor:</strong> Driver에게 직접 지시를 받고 연산을 합니다.</li></ul><h4>Driver ↔ Executor</h4><blockquote>spark conf<br>spark.driver.port (RPC)</blockquote><ul><li><strong>Driver → Executor<br>- </strong>실행할 코드를 직렬화(Serialization)하여 전송합니다.<br>- 처리해야 할 데이터 파티션 정보 및 태스크 실행 명령을 하달합니다.</li><li><strong>Executor → Driver<br>- Heartbeat:</strong> 생존 신호를 주기적으로 보냅니다.<br>- <strong>상태 보고:</strong> 담당 파티션의 작업 진행률, 성공/실패 여부를 전달합니다.</li></ul><p><strong><em>Fault Tolerance:</em></strong><em> Executor가 죽어 보고가 끊기면, 드라이버는 해당 파티션 작업을 다른 Executor에게 재할당하여 전체 작업의 안정성을 보장합니다.</em></p><p><strong>셔플 메타데이터 보고:</strong> 셔플 데이터가 생성되면 그 <strong>위치 정보(주소)</strong>를 드라이버의 <strong>MapOutputTracker</strong>에게 RPC 포트를 통해 보고합니다.</p><h4>BlockManager (Data Transfer)</h4><blockquote>spark conf<br>spark.driver.blockManager.port<br>spark.blockManager.port</blockquote><ul><li><strong>Driver ↔ Executor<br>- Broadcast:<br>1. </strong>드라이버는 브로드캐스트할 데이터를 자신의 <strong>BlockManager</strong>에 바이트 형태로 저장<br><strong>2. </strong>Executor는 작업 중 해당 데이터가 필요하면 먼저 자신의 BlockManager를 확인<br><strong>3. </strong>데이터가 없다면, <strong>드라이버의 BlockManager 포트</strong>로 접속하여 데이터를 직접 <strong>Pull<br>- Collect/Show:<br></strong>df.collect() 등의 액션 수행 시, Executor의 BlockManager에 저장된 결과 데이터를 드라이버의 BlockManager가 요청하여 가져옵니다</li><li><strong>Executor ↔ Executor (Shuffle Data)<br>1. Map Side<br></strong>Executor는 셔플 시 데이터를 로컬 디스크(/tmp/...)에 data와 index 파일로 저장합니다.<br><strong>2. Executor → Driver<br></strong>드라이버는 <strong>RPC(MapOutputTracker)</strong>를 통해 받은 위치 정보를 바탕으로,<br>데이터를 요청하는 Executor에게 어느 주소로 가야 할지 알려줍니다.<br><strong>3. Reduce Side<br></strong>데이터를 가져와야 하는 Executor B는 드라이버가 알려준 주소를 토대로 Executor<strong>A의 BlockManager 포트</strong>에 직접 접속하여 조인이나 그룹화에 필요한 중간 결과물을 직접 가져옵니다.</li></ul><h4>Network Policy</h4><blockquote>Driver Port, BlockManager Port는 설정한 값을 기준으로 사용중일 경우 +1(7080 → 7081) 형태로 할당 받기 때문에 spark conf에 설정한 port를 기준으로 7080–7090 과 같이 Driver → Executor, Executor → Driver 모두 열어줘야 합니다.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e381078adf20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark Deep Dive: Memory]]></title>
            <link>https://medium.com/@seonggil/apache-spark-deep-dive-memory-e8df68f73df7?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8df68f73df7</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark-memory]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 17:47:30 GMT</pubDate>
            <atom:updated>2026-01-16T20:17:57.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtDoX8MsSXjR0jiwxyEomw.png" /></figure><blockquote>Apache Spark의 메모리 할당은 Spark 작업(Job)의 성능을 결정짓는 핵심적인 요소입니다. Spark의 메모리는 연산(Computations), 캐싱(Caching), 그리고 시스템 오버헤드(System Overhead)를 처리하기 위해 여러 구성 요소로 나뉩니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*k38GHsGUqLTyFXQI5vgEGA.png" /></figure><ul><li><strong>Driver Memory:</strong><br>태스크 스케줄링(Task Scheduling) 및 Spark 작업 전반의 관리를 담당하는 드라이버 프로그램에 할당되는 메모리입니다.<br>Driver는 SparkSession/SparkContext를 생성하고, Job을 submit하고,<br>Worker 간의 Task 실행을 조정하는 주요 프로세스입니다.</li><li><strong>Executor Memory:</strong><br>워커 노드(Worker Node)에서 실행되는 각 Executor에 할당되는 메모리입니다. 실제 데이터 처리와 저장(캐싱)이 일어나는 공간입니다.</li></ul><h3>Executor 메모리 아키텍처</h3><blockquote>Spark Executor(JVM)가 실행될 때, 메모리는 크게 <strong>JVM Heap</strong>과 <strong>Off-Heap(JVM 외부)</strong>, 그리고 <strong>Overhead</strong> 영역으로 나뉩니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*1pTLcYHsE6mbQHA9" /></figure><h3>JVM Heap Memory (Inside of JVM)</h3><blockquote>Spark 1.6 이후 도입된 <strong>Unified Memory Manager</strong>는 메모리를 정적으로 나누지 않고, 필요에 따라 유연하게 경계를 조정합니다. Executor 컨테이너 내부의 메모리는 크게 세 가지 영역으로 나뉩니다.</blockquote><p><em>Spark 1.6.0부터 통합 메모리 관리자가 Spark의 기본 메모리 관리자로 설정되었으며, Spark 1.6 이상에서는 </em><em>spark.memory.useLegacyMode=true 매개변수 를 통해 정적 메모리 관리를 활성화할 수 있습니다.</em></p><h4>1. Reserved Memory (Hardcoded to 300MB as of spark 1.6)</h4><blockquote>Spark 1.6 이후 <strong>300MB</strong>로 하드코딩 되어 있습니다.<br>이 공간은 사용자나 데이터 처리에 사용되지 않습니다.</blockquote><p>힙 크기가 이 예약된 메모리의 1.5배(450MB)보다 작으면 Spark는 시작조차 되지 않고 종료됩니다.</p><h4>2. User Memory</h4><blockquote>Spark가 직접 관리하지 않는 영역입니다. 사용자가 코드에서 정의한 커스텀 객체(Custom Objects), UDF, 전역 변수(Broadcast Variables 등)가 저장됩니다.</blockquote><ul><li><strong><em>공식:</em></strong><em> </em><em>(Java Heap — 300MB) X (1 — spark.memory.fraction)</em></li><li><strong><em>기본값:</em></strong><em> 전체 힙의 약 40%</em></li></ul><p><em>이 영역을 너무 줄이면 UDF 실행 중 OOM이 발생할 수 있습니다.</em></p><h4>3. Spark Memory (Unified Region)</h4><blockquote>실제 Spark의 핵심 활동이 일어나는 공간으로, 다시 두 개의 하위 영역으로 나뉘어 상호 공유됩니다.<br>기본값: spark.memory.fraction (기본 0.6, 즉 60%)</blockquote><ul><li><strong>Execution Memory:<br></strong>Join, Shuffle, Aggregation, Sort 등 실제 연산(Computation)을 수행하는 공간입니다. Shuffle 시 발생하는 임시 버퍼(Buffer)들이 이곳에 할당됩니다.</li><li><strong>Storage Memory:<br></strong>cache(), persist() 된 RDD나 DataFrame이 저장되는 공간입니다. Shuffle 데이터나 RDD의 혈통(Lineage) 정보를 저장하여 내결함성(Fault Tolerance)을 보장합니다.</li></ul><h3>Off-Heap Memory (Outside of JVM)</h3><blockquote>Spark는 GC(Garbage Collection) 오버헤드를 피하기 위해 JVM 힙 외부의 메모리를 적극적으로 활용합니다.</blockquote><ul><li><strong><em>설정:</em></strong><em> </em><em>spark.memory.offHeap.enabled=true 및 </em><em>spark.memory.offHeap.size로 활성화.</em></li><li><strong>Tungsten Engine:</strong> Spark의 최적화 엔진인 Tungsten은 데이터를 Java 객체가 아닌 <strong>바이너리(Binary) 형태</strong>로 변환하여 Off-Heap에 직접 저장합니다. 이는 GC의 간섭을 받지 않으며, C++ 수준의 메모리 관리 효율을 제공합니다.</li></ul><p>Off-Heap 메모리는 기본적으로 <strong>Serialized Data Storage(직렬화된 데이터 저장)</strong>나 <strong>네트워크 전송 버퍼(Network Buffer)</strong>로 활용되지만, spark.memory.offHeap.enabled=true 옵션을 활성화하면 Shuffle &amp; Sorting 단계의 실행 버퍼(Execution Buffer)까지 Off-Heap 영역에 할당되어 GC 오버헤드를 제거할 수 있습니다.</p><h3>Unified Memory Manager의 작동 원리</h3><blockquote>Unified Memory 아키텍처에서 Execution과 Storage 영역은 고정된 파티션(Hard Partition) 없이 단일 메모리 풀을 공유하며, 런타임 워크로드의 요구량에 따라 서로의 유휴 자원을 유연하게 차용하는 <strong>동적 점유(Dynamic Occupancy) 메커니즘</strong>을 따릅니다.</blockquote><h4>동적 점유 정책 (Dynamic Occupancy Policy)</h4><blockquote>Unified Memory Manager는 Execution과 Storage 영역 간의 <strong>상호 대여(Mutual Borrowing)</strong> 및 <strong>선점(Preemption)</strong> 메커니즘을 통해 메모리 효율을 극대화합니다</blockquote><ul><li><strong>동적 차용 (Dynamic Borrowing):<br></strong>Execution 영역에 유휴 공간이 존재할 경우 Storage가 이를 차용하여 캐싱에 활용하며, 반대의 경우 Execution이 Storage의 유휴 공간을 점유하여 연산에 활용합니다.</li><li><strong>Execution의 선점 우위 (Preemptive Eviction):<br>- </strong>연산(Execution) 수행 중 메모리가 부족할 경우, Storage가 차용 중인 메모리 블록을 즉시 축출(Evict)하여 공간을 확보합니다.</li></ul><p><em>캐시된 데이터의 손실은 재계산 비용을 발생시킬 뿐이지만, 연산 중인 데이터의 손실은 Task 실패(Failure)로 직결되기 때문입니다.<br>따라서 Spark는 연산의 안정성을 최우선으로 보장합니다.</em></p><ul><li><strong>Storage의 면역 임계값 (Immunity Threshold):<br></strong>spark.memory.storageFraction(기본값 0.5)으로 설정된 영역은 면역 지대(Immune Zone)로 간주됩니다. 이 임계값 내에 저장된 캐시 데이터는 Execution 메모리가 부족하더라도 강제로 축출되지 않습니다</li></ul><h3>Disk Spill의 발생 메커니즘과 비용</h3><blockquote>Task 실행 시 각 스레드(Active Slot)는 파티션 처리를 위해 Execution Memory를 점유합니다. 가용 메모리가 임계치에 도달하면 <strong>Spill(디스크 유출)</strong> 메커니즘이 트리거됩니다</blockquote><h4>Spill 처리 프로세스 (Step-by-Step)</h4><blockquote>Execution Memory가 <strong>500MB</strong>이고 실행 중인 코어가 2개(N = 2)라면,<br>각 태스크는 최소 <strong>125MB</strong>(500 / 4(2N))에서 최대 <strong>250MB</strong>(500 / 2) 사이의 메모리 내에서만 동작해야 합니다.</blockquote><blockquote>최소한의 메모리를 확보하지 못하면 해당 태스크는 대기하거나 acquireMemory()를 통해 공간이 날 때까지 기다립니다.</blockquote><ol><li><strong>In-Memory Buffer 할당:<br></strong>SortMergeJoin 등의 연산 수행 시, Spark는 ExternalAppendOnlyMap 혹은 ExternalSorter와 같은 인메모리 페이지(Page) 버퍼에 데이터를 적재합니다.</li><li><strong>리소스 요청 및 부족 감지:<br></strong>버퍼가 포화 상태에 이르면 MemoryManager에 추가 페이지 할당을 요청(acquireMemory())합니다.</li><li><strong>Spill 트리거 (Spill Trigger):<br></strong>Unified Memory 내의 가용 공간이 고갈되고, Storage로부터 축출할 수 있는 공간조차 없을 경우 Spill이 발동됩니다.</li><li><strong>직렬화 및 디스크 쓰기 (Serialization &amp; I/O Overhead):<br></strong>메모리에 상주하던 데이터를 <strong>정렬(Sort)</strong> 후 <strong>직렬화(Serialize)</strong>하여 로컬 디스크의 임시 디렉토리(spark.local.dir)에 기록합니다.<br><strong><em>- 성능 영향:</em></strong><em> 이 과정에서 직렬화로 인한 CPU 부하와 Disk I/O Latency가 동시에 발생하여 처리 속도가 급격히 저하됩니다.</em></li><li><strong>병합 (Merge Sort):<br></strong>Task 완료 시점에 디스크에 분산된 Spill 파일들과 메모리의 잔존 데이터를 다시 읽어들이며 병합 정렬(Merge Sort)을 수행합니다.</li></ol><p>Spill은 OOM(Out Of Memory)을 방지하기 위한 방어 기제이나, 과도한 발생은 심각한 병목(Bottleneck)이 발생할 수 있습니다.<em><br>Spark UI의 Stage 탭에서 </em><em>Spill (Memory) 및 </em><em>Spill (Disk) 지표를 모니터링할 수 있습니다.</em></p><h3>OOM 분석 및 성능 최적화</h3><h4>Case 1: Executor OOM</h4><blockquote>java.lang.OutOfMemoryError: Java heap space</blockquote><ul><li><strong>원인 A (Data Skew):</strong> 특정 파티션 키(Key)에 데이터가 편중되어, 단일 Task가 처리해야 할 데이터 양이 Executor의 힙 메모리 한계를 초과함<br><strong><em>→ </em></strong><em>Key Salting 기법 적용 또는 </em><em>repartition()을 통한 데이터 재분배.</em></li><li><strong>원인 B (High Memory Footprint):</strong> User Memory 영역에 고비용 객체(대용량 Map, List 등)가 다수 생성됨<br><strong><em>→ </em></strong><em>어플리케이션 로직 최적화 또는 </em><em>spark.memory.fraction 하향 조정을 통한 User Memory 공간 확보</em></li></ul><h4>Case 2: Container killed by YARN for exceeding memory limits</h4><ul><li><strong>원인:</strong> JVM Heap 외적으로 사용되는 <strong>Off-Heap Overhead</strong>(Netty Buffer, Thread Stack 등)가 컨테이너 설정 한도를 초과함<br><strong><em>→ </em></strong><em>spark.executor.memoryOverhead 파라미터 상향 조정</em></li></ul><p><strong>기준:</strong> Max(spark.executor.memory * 0.10, 384MB)</p><p><em>conf spark.executor.memoryOverhead=2048 등으로 여유 공간 확보.</em></p><h4>Case 3: Driver OOM</h4><ul><li><strong>원인:</strong> collect() 호출로 인해 Executor의 대용량 결과 데이터가 Driver로 일시에 전송됨<br><strong><em>→ </em></strong><em>collect() 대신 </em><em>toLocalIterator()를 사용하여 데이터 스트리밍 처리.</em><br><strong><em>→ </em></strong><em>spark.driver.maxResultSize 설정 변경(기본 1GB)</em><br><strong><em>→ </em></strong><em>Driver 메모리 리소스 증설 (</em><em>spark.driver.memory)</em></li></ul><h4>Case 4: 과도한 Spill로 인한 Latency 증가</h4><ul><li><strong>원인:</strong> 데이터 규모 대비 파티션 수가 부족하여, 파티션 당 크기가 Executor 메모리 용량을 상회함.<br><strong><em>→ </em></strong><em>spark.sql.shuffle.partitions (기본 200) 값을 상향 조정하여 파티션 당 데이터 크기를 적정 수준(128MB~200MB)으로 유지</em></li></ul><h3>Shuffle 발생 시 메모리 점유 및 할당 메커니즘</h3><blockquote>셔플링은 크게 <strong>Shuffle Write (Map Side)</strong>와 <strong>Shuffle Read (Reduce Side)</strong> 두 단계로 나뉩니다. 이 과정에서 Spark는 <strong>Execution Memory</strong> 영역을 사용하며, Tungsten 엔진의 페이지 기반 관리가 본격적으로 작동합니다.</blockquote><h4><strong>1. Map Side: Shuffle Write 단계의 메모리 할당</strong></h4><blockquote>Map Task는 데이터를 처리한 후, 다음 스테이지의 Reducer가 가져갈 수 있도록 파티션별로 데이터를 분류하고 정렬해야 합니다. 이 과정에서 <strong>In-Memory Buffer</strong>가 핵심적인 역할을 합니다.</blockquote><h4>1–1. 데이터 구조: PartitionedAppendOnlyMap &amp; PartitionedPairBuffer</h4><blockquote>Spark는 들어오는 레코드(Record)를 즉시 디스크에 쓰지 않고, 먼저 메모리 버퍼에 채웁니다. 연산 종류에 따라 두 가지 자료구조 중 하나를 할당받습니다.</blockquote><ul><li><strong>PartitionedAppendOnlyMap:<br></strong>reduceByKey나 aggregateByKey처럼 Aggregation(집계)이 필요한 경우 사용합니다. 해시 테이블과 유사하게 Key가 같으면 값을 갱신(Update)하며 메모리를 효율적으로 사용합니다.</li><li><strong>PartitionedPairBuffer:<br></strong>sortByKey나 groupByKey처럼 단순 정렬이나 그룹핑만 필요할 때 사용합니다. 단순히 데이터를 차곡차곡 쌓는 배열(Array) 형태입니다.</li></ul><h4>1–2. 메모리 점유 방식 (Pointer + Page)</h4><blockquote>이 버퍼들은 단순히 자바 객체를 저장하는 것이 아니라, <strong>Tungsten 방식</strong>으로 메모리를 점유합니다.</blockquote><ol><li><strong>Pointer Array (포인터 배열):<br>- </strong>데이터의 주소값(Pointer)과 파티션 ID만을 저장하는 Long 타입 배열을 할당합니다.<br>- 정렬(Sorting)이 필요할 때 실제 무거운 데이터를 옮기지 않고, 이 **가벼운 포인터 배열만 퀵 소트(Quick Sort)**하여 속도를 높입니다.</li><li><strong>Data Pages (데이터 페이지):<br>- </strong>실제 Key와 Value 데이터는 OS의 Page 단위(기본 64MB 등)로 할당된 메모리 블록에 바이너리 형태로 연속해서 기록됩니다.<br>- 이 방식은 메모리 단편화(Fragmentation)를 막고 CPU 캐시 적중률(Cache Locality)을 높입니다.</li></ol><h4>1-3. 할당과 Spill의 임계점</h4><blockquote>데이터가 계속 들어오면 메모리 매니저는 다음과 같은 과정을 반복합니다.</blockquote><ol><li><strong>Check:</strong> 현재 버퍼(Pointer Array + Data Pages)의 크기가 임계치를 넘었는지 확인합니다.</li><li><strong>Request:</strong> UnifiedMemoryManager에게 <strong>Execution Memory</strong> 추가 할당을 요청(acquireMemory())합니다.</li><li><strong>Spill: </strong>요청이 거절되거나(메모리 부족), 컬렉션 내부의 포인터 배열이 한계에 도달하면 <strong>Spill</strong>이 트리거됩니다.</li><li>메모리에 있는 데이터를 파티션 ID 기준으로 정렬하여 디스크에 쓰고, 메모리를 비웁니다(Free).</li></ol><h4>2. Reduce Side: Shuffle Read 단계의 메모리 할당</h4><blockquote>Reducer는 여러 Mapper로부터 자신에게 할당된 파티션의 데이터 블록을 네트워크를 통해 가져옵니다.</blockquote><h4>2–1. Fetch &amp; Buffer (가져오기 및 버퍼링)</h4><ul><li><strong>ExternalAppendOnlyMap:</strong> Reduce 단계에서도 데이터 집계나 정렬이 필요하다면 Map Side와 유사한 ExternalAppendOnlyMap을 할당합니다.</li><li>네트워크 버퍼: 네트워크를 통해 들어오는 데이터는 일시적으로 네트워크 버퍼(Netty Buffer, Off-Heap)를 거쳐 Executor의 <strong>Heap(또는 Off-Heap) Execution Memory</strong>로 복사됩니다.</li></ul><h4>2–2. Merge Sort (병합 정렬)와 메모리</h4><blockquote>Spill 없이 모든 데이터가 메모리에 들어올 수 있으면 좋지만, 대용량 처리 시에는 <strong>Memory-Disk 하이브리드 방식</strong>이 작동합니다.</blockquote><ol><li><strong>In-Memory Merge:<br></strong>Mapper에서 가져온 데이터 블록들을 메모리 맵(Map)에 넣으면서 실시간으로 집계(Merge)를 수행합니다.</li><li><strong>Spill to Disk:<br></strong>Map Side와 마찬가지로 Execution Memory가 꽉 차면, 현재까지 집계된 맵의 내용을 디스크로 Spill 합니다</li><li><strong>Global Merge:<br></strong>최종적으로 디스크에 Spill된 여러 파일들과, 현재 메모리에 남아있는 데이터를 하나로 합칩니다.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8df68f73df7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[TIL — 42일차] 데이터 엔지니어링: Hadoop, Spark (5)]]></title>
            <link>https://medium.com/@seonggil/til-42%EC%9D%BC%EC%B0%A8-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%97%94%EC%A7%80%EB%8B%88%EC%96%B4%EB%A7%81-hadoop-spark-5-c134bb0abff7?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/c134bb0abff7</guid>
            <category><![CDATA[emr]]></category>
            <category><![CDATA[til]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sparkml]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 08:42:32 GMT</pubDate>
            <atom:updated>2026-01-07T08:42:32.629Z</atom:updated>
            <content:encoded><![CDATA[<h3>[TIL — 42일차] 데이터 엔지니어링: Hadoop, Spark (5)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*becuWxq_pF6CP785i8T7zA.png" /></figure><h3>Spark ML 소개</h3><h4>Spark ML</h4><blockquote>머신러닝 관련 다양한 알고리즘, 유틸리티로 구성된 라이브러리</blockquote><ul><li><strong>Classification</strong>:<br>Logistic regression, Decision Tree, Random Forest, Gradient-boosted Tree 등</li><li><strong>Regression</strong>:<br>Linear Regression, Decision Tree, Random Forest, Gradient-boosted Tree 등</li><li><strong>Clustering</strong>:<br>K-means, LDA, GMM 등</li><li><strong>Collaborative Filtering (추천)</strong>:<br>명시적인 피드백(리뷰 평점)과 암묵적인 피드백 기반(클릭, 구매)</li></ul><p>RDD 기반과 데이터 프레임 기반 버전이 존재 spark.ml을 사용할 것, spark.mllib는 RDD 기반</p><h4>Spark ML의 장점</h4><ul><li>원스톱 ML 프레임워크<br>- 데이터 프레임과 Spark SQL 등을 이용해 전처리<br>- Spark ml를 이용해 모델 빌딩<br>- ML Pipeline을 통해 모델 빌딩 자동화<br>- MLflow로 모델 관리 및 서빙</li><li>대용량 데이터 처리도 가능</li></ul><h4>Spark ML 기반 모델 빌딩 기본 구조</h4><blockquote>다른 라이브러리를 사용한 모델 빌딩과 크게 다르지 않음</blockquote><ol><li>훈련 데이터 전처리</li><li>모델 빌딩</li><li>모델 검증</li></ol><ul><li><strong>Scikit-Learn과 비교했을 때 장점<br>- 데이터의 크기</strong> : Scikit-Learn은 하나의 컴퓨터에서 동작, Spark ML은 여러 서버 위에서 동작<br>- Spark은 ML Pipeline을 통해 모델 개발의 반복을 쉽게 해 줌</li></ul><h3>MLflow</h3><ul><li>모델의 관리와 서빙을 위한 Ops 관련 기능 제공</li><li>모델 개발과 테스트, 관리, 서빙까지 제공해 주는 End-to-End 프레임워크</li><li>Python, Java, R, API 지원</li><li>트래킹(Tracking), 모델(Models), 프로젝트(Projects) 지원</li></ul><h3>Spark ML Pipeline 살펴보기</h3><h4>모델 빌딩과 관련된 문제</h4><ul><li><strong>훈련 데이터의 관리가 안됨</strong></li><li><strong>모델 훈련 방법이 기록이 안됨</strong><br>- 어떤 훈련 데이터를 사용했는가<br>- 어떤 피쳐들을 사용했는가<br>- 하이퍼 파라미터는 무엇을 사용했는가</li><li><strong>모델 훈련에 많은 시간 소요</strong><br>- 모델 훈련이 자동화가 안된 경우 매번 각 스텝을 노트북 등에서 직접 수행<br>- 에러가 발생할 여지가 많음</li></ul><h4>ML Pipeline</h4><ul><li>데이터 과학자가 머신러닝 개발과 테스트를 쉽게 해주는 기능 (데이터 프레임 기반)</li><li>머신러닝 알고리즘에 관계없이 일관된 형태의 API 사용</li><li>ML 모델 개발과 테스트를 반복 가능하게 해 줌</li><li><strong>구성 요소<br>- DataFrame</strong>:<br>데이터 프레임이 기본 데이터 포맷으로 사용되며, csv, json, parquet, JDBC 지원<br>- <strong>Transformer</strong> :<br>입력 데이터 프레임을 하나 이상의 컬럼을 추가한 데이터 프레임으로 변환<br>- <strong>Estimator</strong> : 머신러닝 알고리즘에 해당, fit이 메인 함수 (<strong>입력</strong> : 훈련데이터, <strong>출력</strong> : 머신러닝 모델)<br>- <strong>Parameter</strong> : Transformer와 Estimator의 공동 API로 다양한 인자를 적용 (하이퍼 파라미터)</li></ul><h3>클라우드 기반 Spark 클러스터</h3><h4>AWS에서 Spark을 실행</h4><blockquote>EMR(Elastic MapReduce) 위에서 실행하는 것이 일반적</blockquote><ul><li>AWS의 Hadoop 서비스 (On-demand Hadoop)</li><li>Hadoop(YARN), Spark, Hive, Notebook 등이 설치되어 제공</li><li>EC2 서버를 worker node로 사용하고 S3를 HDFS로 사용</li><li>AWS 내의 다른 서비스와 연동이 쉬움 (Kinesis, DynamoDB, Redshift 등)</li></ul><h4>Spark on EMR</h4><ol><li>AWS의 EMR 클러스터 생성</li><li>EMR 생성 시 Spark 실행 (옵션으로 선택),<br>S3를 기본 파일 시스템으로 선택</li><li>EMR의 마스터 노드를 드라이버 노드로 사용</li></ol><p><em>마스터 노드를 SSH로 로그인 (spark-submit 사용), Spark의 Cluster 모드에 해당</em></p><h4><strong>EMR 클러스터 생성 과정</strong></h4><ol><li>Spark / Zeppelin이 포함된 옵션 선택</li></ol><p>클러스터 사양(m5.xlarge 노드 3개) 선택: <em>(4CPU + 16GB) * 2</em></p><ol><li>EMR 클러스터 생성 완료</li><li>마스터 노드의 포트번호 22번 열기</li><li>Spark History Server 확인</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c134bb0abff7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[TIL — 41일차] 데이터 엔지니어링: Hadoop, Spark (4)]]></title>
            <link>https://medium.com/@seonggil/til-41%EC%9D%BC%EC%B0%A8-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%97%94%EC%A7%80%EB%8B%88%EC%96%B4%EB%A7%81-hadoop-spark-4-2c35987efcfc?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c35987efcfc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[bucketing]]></category>
            <category><![CDATA[til]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 08:22:54 GMT</pubDate>
            <atom:updated>2025-12-24T08:22:54.680Z</atom:updated>
            <content:encoded><![CDATA[<h3>[TIL — 41일차] 데이터 엔지니어링: Hadoop, Spark (4)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*becuWxq_pF6CP785i8T7zA.png" /></figure><h3>Spark 내부동작</h3><h4>Spark 파일포맷</h4><blockquote>Spark을 사용할 때 작업에 맞는 최적화된 파일(파일포맷)을 사용해야 함</blockquote><ul><li><strong>Unstructured (비구조화)</strong>: Text</li><li><strong>Semi-structured (반구조화)</strong>: json, xml, csv</li><li><strong>Structured (구조화)</strong>: parquet, avro, orc, sequencefile</li></ul><h4>Spark의 주요 파일 포맷</h4><ul><li><strong>Splittable</strong> : HDFS 데이터 블록의 Partition으로 바로 올라갈 수 있는지 여부</li><li><strong>Human readable</strong> : 사람이 읽을 수 있는지 여부</li><li><strong>Nested structure support</strong> : subfield를 지원하는지 여부</li><li><strong>Schema evolution</strong> : 스키마가 다른 데이터끼리 사용 가능한지 여부</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*F-O2Q2NpYaz4qgKRrr7Xrw.png" /></figure><ul><li><em>Spark의 기본 파일 포맷: Parquet</em></li><li><em>압축되면 Splittable 하지 않음 (압축 방식에 따라 다름 — snappy 압축이라면 Splittable)</em></li></ul><p><em>gzip으로 압축된 CSV, JSON 파일은 Splittable하지 않기 때문에 하나의 executor가 일단 처리하게 되며 메모리 에러가 날 확률이 높음</em></p><p><a href="https://parquet.incubator.apache.org/">Parquet</a></p><h3>Execution Plan</h3><blockquote>Spark Dataframe 기반으로 작성된 Query는 Lazy하게 실행되며,<br>실행 시 사용자가 작성한 Query를 기반으로 Execution Plain을 효율적으로 변경하여 실행시켜줌</blockquote><h4>Transformation &amp; Action</h4><blockquote>Transformation은 Action을 실행하기 전까지 실행되지 않으며(Lazy), Action 함수를 실행 시 실제 연산을 수행함</blockquote><ul><li><strong>Transformation<br></strong>- Narrow Dependencies (select, filter, map, …): <br>독립적인 파티션 레벨 작업, Shuffle이 발생하지 않음<br>- Wide Dependencies (groupby, reduceby, partitionby, repartition, …): Shuffling이 필요한 작업</li><li><strong>Action (Read, Write, Show, Collect):<br></strong>아직 실행되지 않고 대기중인 Transformation을 실제로 수행시키는 연산</li></ul><h4>Jobs, Stages, Tasks</h4><blockquote>Action -&gt; Job -&gt; 1+ Stages -&gt; 1+ Tasks</blockquote><ul><li><strong>Action</strong> : Job을 하나 만들고 코드가 실제로 실행</li><li><strong>Job</strong> : Stage는 Shuffling이 발생하는 경우 새로 생김</li><li><strong>Stage</strong> : DAG의 형태로 구성된 Task 존재, Task는 병렬 실행 가능</li><li><strong>Task</strong> : 가장 작은 실행 유닛으로 Executor에 의해 실행</li></ul><pre>(spark.read.option(&quot;header&quot;, True).csv(“test.csv”)<br>.select(&quot;name&quot;, &quot;gender&quot;)<br>.groupby(&quot;gender&quot;)<br>.count()<br>.show())</pre><ul><li><strong>Job 0: CSV 헤더 읽기 (Metadata)</strong></li><li><strong>Job 1 (실제 데이터 처리 및 집계 </strong><strong>show)</strong></li><li><strong>Stage 1 (Scan &amp; Partial Count):</strong> 파일을 읽고, 필요한 컬럼만 선택한 뒤, 각 파티션 내에서 성별(gender)별로 부분 합계(Partial count)를 계산</li><li><strong>Stage 2 (Shuffle &amp; Global Count):</strong> 네트워크를 통해 같은 성별 데이터를 한 곳으로 모으는 <strong>Shuffle</strong>이 발생하고, 최종 카운트를 계산하여 결과를 만듬</li></ul><h3>Bucketing &amp; Partitioning</h3><blockquote>HDFS 데이터나 입력 파티션을 처리 형태에 맞춰 최적화할 수 있다면, 처리 시간을 단축하고 리소스를 덜 사용할 수 있음</blockquote><h4>Partitioning: File System(물리적 폴더 구조화)</h4><blockquote>데이터를 특정 컬럼(Partition Key)의 값에 따라 <strong>디렉터리 단위로 나누어 저장</strong>하는 방식</blockquote><ul><li>.../year=2025/month=12/day=24/data.parquet와 같이 계층적 폴더 구조를 생성</li><li><strong>(Data Skipping):</strong> 쿼리 조건에 Partition Key가 포함되면, 해당 폴더 외의 데이터는 아예 읽지 않을 수 있으며, 이를 통해 I/O 성능이 극적으로 향상</li></ul><pre>df.write.partitionBy(&quot;year&quot;, &quot;month&quot;, &quot;day&quot;) \<br>  .mode(&quot;overwrite&quot;) \<br>  .parquet(&quot;/mnt/data/logs&quot;)</pre><ul><li><strong>Cardinality:<br></strong>성별(2개)처럼 값이 적은 컬럼은 좋지만, user_id처럼 수백만 개인 컬럼을 파티션 키로 잡으면 너무 많은 폴더와 <strong>작은 파일(Small File Problem)</strong>이 생성되어 네임노드 메모리 부하와 쿼리 속도 저하를 초래할 수 있음</li><li><strong>Retention:<br></strong>특정 날짜의 폴더만 삭제하면 되므로 데이터 생명주기 관리가 쉬움</li></ul><h4>Bucketing (데이터 클러스터링)</h4><blockquote>특정 컬럼의 해시(Hash) 값을 기준으로 데이터를 <strong>고정된 수의 파일(Bucket)로 분산 저장</strong>하는 방식</blockquote><ul><li>지정된 컬럼 값을 해싱하여 0~N번 버킷 중 어디에 담길지 결정합니다. 동일한 값은 항상 같은 버킷 파일에 저장</li><li><strong>(Shuffle Elimination):</strong> Join이나 Aggregation 수행 시, 데이터가 이미 같은 기준(ID 등)으로 모여 있고 정렬되어 있어 <strong>셔플(Shuffle) 과정을 생략</strong>하거나 대폭 줄일 수 있음</li></ul><pre># 반드시 Hive Metastore에 테이블로 저장해야 정보가 유지됨<br>df.write.format(&quot;parquet&quot;) \<br>  .bucketBy(20, &quot;user_id&quot;) \<br>  .sortBy(&quot;timestamp&quot;) \<br>  .saveAsTable(&quot;bucketed_user_logs&quot;) </pre><ul><li><strong>Metastore 의존성:</strong> 버킷 정보(버킷 수, 기준 컬럼)는 Hive Metastore에 저장됨, 따라서 단순히 파일 경로로 읽기(spark.read.parquet)보다는 spark.table(&quot;table_name&quot;)으로 읽어야 최적화 혜택을 온전히 누릴 수 있음</li><li><strong>Join 최적화의 조건:</strong> 두 테이블을 Join할 때 버킷 최적화가 작동하려면<br><strong>1) Join 키가 버킷 키와 같아야 함</strong>, <strong>2) 버킷 개수가 같거나 배수 관계</strong>여야 효과가 극대화됨</li></ul><p>보통 <strong>Partitioning + Bucketing</strong>을 조합함.<br>날짜(date)로 파티션을 나누어 범위를 좁히고, 그 안에서 user_id로 버킷을 나누어 Join 성능을 확보하는 방식으로 사용함</p><p><em>버킷당 파일 크기가 최소 </em><strong><em>128MB~256MB</em></strong><em> 정도를 유지하도록 버킷 개수를 조절하는 것이 좋음</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c35987efcfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[TIL — 40일차] 데이터 엔지니어링: Hadoop, Spark (3)]]></title>
            <link>https://medium.com/@seonggil/til-40%EC%9D%BC%EC%B0%A8-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%97%94%EC%A7%80%EB%8B%88%EC%96%B4%EB%A7%81-hadoop-spark-3-e3f3b3d0dea1?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3f3b3d0dea1</guid>
            <category><![CDATA[til]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark-sql]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 11:57:28 GMT</pubDate>
            <atom:updated>2025-12-05T11:58:32.576Z</atom:updated>
            <content:encoded><![CDATA[<h3>[TIL — 40일차] 데이터 엔지니어링: Hadoop, Spark (3)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*becuWxq_pF6CP785i8T7zA.png" /></figure><h3>Spark 프로그래밍: SQL</h3><blockquote>Spark SQL과 Spark DataFrame의 차이점과 Spark SQL의 사용법</blockquote><h4>SQL의 중요성</h4><ul><li>데이터 분야의 필수적인 기본 기술</li><li>구조화된 데이터를 처리한다면 SQL은 데이터 규모와 관계없이 사용됨</li></ul><h4>Spark SQL</h4><blockquote>구조화된 데이터 처리를 위한 Spark Module</blockquote><ul><li>DataFrame 작업을 SQL로 처리 가능</li><li>HQL(Hive Query Language)과 호환 제공<br><em>Hive Table을 읽고 쓸 수 있음 (Hive Metastore)</em></li></ul><h4>Spark SQL 사용법</h4><ol><li>데이터 프레임을 기반으로 테이블 뷰 생성<br><strong>- </strong><strong>createOrReplaceTempView:</strong> spark Session이 살아있는 동안 존재<br><strong>- </strong><strong>createOrReplaceGlobalTempView:</strong> Spark 드라이버가 살아있는 동안 존재</li><li>Spark Session의 SQL 함수로 SQL 결과를 데이터 프레임으로 받음</li></ol><pre>namegender_df.createOrReplaceTempView(&quot;namegender&quot;)<br>namegender_group_df = spark.sql(&quot;&quot;&quot;<br>  SELECT<br>  gender<br>  , count(1)<br>  FROM namegender<br>  GROUP BY 1<br>&quot;&quot;&quot;)<br>print(namegender_group_df.collect())</pre><h3>Aggregation, JOIN</h3><blockquote>SQL에서 지원하는 다양한 Aggregation과 JOIN 방식을 Spark SQL에서도 지원함</blockquote><h4>Aggregation 함수</h4><ul><li><strong>Group By</strong> : SUM, MIN, MAX, AVG, COUNT, …</li><li><strong>Window</strong> : ROW_NUMBER, FIRST_VALUE, LAST_VALUE, …</li><li><strong>Rank</strong></li></ul><h4>Join 함수</h4><blockquote>SQL JOIN은 두 개 혹은 그 이상의 테이블을 공통 필드를 가지고 병합</blockquote><ul><li><strong>Shuffle JOIN(</strong>Shuffle Hash Join, Sort-Merge Join<strong>):<br>대부분의 경우 사용</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*JyxGggv0OzoB8W2BXZXGDw.png" /></figure><ul><li><strong>Broadcast JOIN:<br></strong>큰 데이터와 작은 데이터 간의 조인 시 작은 데이터를 모든 파티션으로 broadcasting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*vctwypYot0-HlXjZEWKGHg.png" /><figcaption><strong>Broadcast JOIN</strong></figcaption></figure><p><em>브로드캐스트 조인은 </em><em>Key-Value 쌍을 기준으로 파티션을 재배치하는 </em><strong><em>파티셔닝(Partitioning)</em></strong><em> 작업이 아니기 때문에, </em><strong><em>특정 키가 단일 파티션에 모여 있다는 것을 보장하지 않음</em></strong></p><h3>UDF (User Defined Function)</h3><blockquote>DataFrame이나 SQL에서 적용할 수 있는 사용자 정의 함수</blockquote><ul><li>데이터 프레임의 경우 .withColumn함수와 같이 사용하는 것이 일반적</li><li>Spark SQL에서도 사용 가능</li><li>Aggregation 용 UDAF(User Defined Aggregation Function)도 존재<br>- Group By에서 사용되는 SUM, AVG와 같은 함수를 만드는 것<br>- <em>PySpark에서 지원하지 않고, Scalar / JAVA를 사용해야 함</em></li></ul><h4><strong>‘Name’ 컬럼을 대문자로 변환한 </strong><strong>‘Curated Name’ 컬럼을 생성</strong></h4><pre>import pyspark.sql.functions as F<br>from pyspark.sql.types import *<br><br>upperUDF = F.udf(lambda z:z.upper())<br>df.withColumn(&quot;Curated Name&quot;, upperUDF(&quot;Name&quot;))</pre><p>z 에는 하나의 row의 값이 들어오게 됨</p><p>UDF는 DataFrame의 기본 최적화(Catalyst Optimizer)를 우회하고,<br>Spark의 JVM(Java Virtual Machine) 환경에서 Python 프로세스로 데이터를 <strong>직렬화/역직렬화</strong>하여 전달해야 하므로 <strong>성능 저하</strong>가 발생함<br><em>→ 가능하다면 내장된 함수를 사용할 것 (</em><em>F.upper())</em></p><h4><strong>SQL 활용</strong></h4><blockquote>register 를 통해 SparkSQL에서도 UDF를 사용할 수 있음</blockquote><pre>def plus(x, y):<br> return x + y<br><br>plusUDF = spark.udf.register(&quot;plus&quot;, plus)<br>spark.sql(&quot;SELECT plus(1, 2)&quot;).show()<br><br># 3</pre><h4>UDF : Pandas UDF Scalar 함수 사용해 보기</h4><blockquote>기존에 정의한 UDF는 하나의 ROW를 대상으로 처리하여 연산 시 성능저하가 발생함</blockquote><ul><li>Pandas UDF의 경우 Series를 인자로 받아 처리(벡터화 UDF)</li></ul><p><em>기본적으로 Pandas Series의 벡터 연산 규칙을 따름</em></p><ul><li>[1, 2, 3] + 1 = [2, 3, 4]</li><li>[1, 2, 3] + [1, 2] = ValueError</li><li>[1, 2, 3] + [1, 2, 3] = [2, 4, 6]</li></ul><pre>from pyspark.sql.functions import pandas_udf<br>import pandas as pd<br><br># def pandas_udf(f=None, returnType=None, functionType=None):<br>@pandas_udf(StringType())<br>def upper_udf2(s: pd.Series) -&gt; pd.Series:<br> return s.str.upper()<br><br>upperUDF = spark.udf.register(&quot;upper_udf&quot;, upper_udf2)<br>df.select(&quot;Name&quot;, upperUDF(&quot;Name&quot;)).show()<br>spark.sql(&quot;&quot;&quot;<br>  SELECT<br>    name<br>    , upper_udf(name) AS `Curated Name`<br>  FROM test<br>&quot;&quot;&quot;).show()</pre><h3>Hive MetaStore 사용하기</h3><blockquote>Catalog: 테이블과 뷰에 관한 메타 데이터 관리<br>기본으로 메모리 기반 카탈로그 ,세션이 끝나면 사라짐</blockquote><ul><li><strong>테이블 관리 방식</strong> : 데이터베이스라 부르는 폴더와 같은 구조로 관리</li><li><strong>메모리 기반 테이블 (View)</strong> : 임시테이블로 앞서 사용한 형태</li><li><strong>스토리지 기반 테이블: </strong>기본적으로 HDFS와 parquet 포맷 사용<br><em>Managed Table, Unmanaged(External) Table</em></li></ul><pre>spark = SparkSession \<br>    .builder \<br>    .appName(&quot;Python Spark Hive&quot;) \<br>    .enableHiveSupport() \ # enable Hive MetaStore<br>    .getOrCreate()</pre><h4>Spark SQL : Managed Table 사용법</h4><ul><li>두 가지 테이블 생성 방법<br>- dataframe.saveAsTable(“table_name”)<br>- SQL 문법 사용 : CREATE TABLE, CTAS</li><li>spark.sql.warehouse.dir가 가리키는 위치에 데이터가 저장</li><li>JDBC / ODBC 등으로 Spark와 연결해서 접근 가능 (Tableau, Power BI)</li></ul><h4>Spark SQL : Unmanaged (External) Table 사용법</h4><ul><li>이미 HDFS에 존재하는 데이터에 스키마를 정의해서 사용</li><li>메타 데이터만 카탈로그에 기록<br>- 데이터는 이미 존재<br>- External Table은 삭제되어도 데이터는 그대로</li></ul><h3>Unit Test</h3><blockquote>코드 상의 특정 기능을 테스트하기 위해 작성된 코드</blockquote><ul><li>보통 정해진 입력을 주고 예상된 출력이 나오는지 테스트</li></ul><p>기존 Unit Test 작성 방식과 동일하게 setUp(SparkSession), test_A, test_B 형식으로 작성할 수 있음</p><pre># /tests/test_df.py<br><br>class UtilsTestCase(TestCase):<br>    spark = None<br><br>    @classmethod<br>    def setUpClass(cls) -&gt; None:<br>        cls.spark = SparkSession.builder \<br>            .appName(&quot;Spark Unit Test&quot;) \<br>            .getOrCreate()<br><br><br>    def test_A(self):<br>        ...<br><br><br>    def test_B(self):<br>        ...<br><br><br>    @classmethod<br>    def tearDownClass(cls) -&gt; None:<br>        cls.spark.stop() </pre><pre>$ python -m unittest test_df.py</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f3b3d0dea1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[TIL — 39일차] 데이터 엔지니어링: Hadoop, Spark (2)]]></title>
            <link>https://medium.com/@seonggil/til-39%EC%9D%BC%EC%B0%A8-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%97%94%EC%A7%80%EB%8B%88%EC%96%B4%EB%A7%81-hadoop-spark-2-9236d68a7dab?source=rss-9e5e0974a617------2</link>
            <guid isPermaLink="false">https://medium.com/p/9236d68a7dab</guid>
            <category><![CDATA[data-partitioning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pyspark-dataframes]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[til]]></category>
            <dc:creator><![CDATA[Seonggil Jeong]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 04:52:48 GMT</pubDate>
            <atom:updated>2025-12-03T04:52:48.598Z</atom:updated>
            <content:encoded><![CDATA[<h3>[TIL — 39일차] 데이터 엔지니어링: Hadoop, Spark (2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*becuWxq_pF6CP785i8T7zA.png" /></figure><h3>Spark 데이터 시스템 아키텍처</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMSke9Bcko7zXZDn7CQLtQ.png" /></figure><h4>데이터 병렬처리</h4><blockquote>데이터가 먼저 분산되어 있어야하며, Spark에서는 이를 파티션(Partition)이라 부름. 각 파티션은 각각 따로 동시 처리됨</blockquote><ul><li>spark.sql.files.maxPartitionBytes : 128MB, 파일을 읽어올 때 128MB로 split해서 읽어옴 (256MB → [128MB, 128MB] (partition 2개))</li></ul><p><em>데이터 분산 → 파티셔닝 → 병렬처리</em></p><h4>Spark 데이터 처리 흐름</h4><ul><li>데이터 프레임은 작은 파티션들로 구성 <em>수정 불가 (Immutable)</em></li><li>입력 데이터 프레임을 원하는 결과 도출까지 다른 데이터 프레임으로 계속 반환</li><li>sort, group by, filter, map, join 등의 오퍼레이션 작업을 거침</li></ul><h4>셔플링</h4><blockquote>특정 키 값을 기준으로 데이터를 다시 파티셔닝할 경우 셔플링이 발생함</blockquote><ul><li>명시적으로 파티션을 새롭게 쓰거나(파티션 수 줄이기) aggregation, sorting 시 셔플링이 발생하게 됨</li><li>셔플링이 발생할 때 네트워크를 타고 데이터가 이동하게 됨</li><li>spark.sql.shuffle.partitions : 몇 개의 파티션이 결과로 만들어질지 설정</li></ul><p>random, hashing partition, range partition이 있으며,<br><strong>aggregation 시 hashing partition</strong>,<br><strong>sorting 시 range partition</strong>을 사용</p><p><a href="https://medium.com/@seonggil/apache-spark-spark-shuffle-deep-dive-0e316cdbb36a">Apache Spark Deep Dive: Shuffle</a></p><h4>Data Skewness</h4><blockquote>Data partitioning은 데이터 처리에 병렬성을 주지만, 데이터가 균등하게 분포되지 않는 경우가 생길 수 있음</blockquote><p>사용자 아이디를 기준으로 partitioning 시 특정 사용자의 데이터가 많다면, 각 파티션의 데이터 크기가 불균등해짐<br><em>→ 특정 파티션에 처리시간만 늘어나게 되면서 병렬처리의 장점이 없어질 수 있음</em></p><h3>Spark 데이터 구조</h3><blockquote>RDD, DataFrame, Dataset (Immutable Distributed Data)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xj-_PQFOizXPcqAjnV8vTw.png" /></figure><ul><li>2016년에 DataFrame과 Dataset은 하나의 API로 통합됨</li></ul><h4>RDD (Resilient Distributed Dataset)</h4><blockquote>로우레벨 데이터로 클러스터내의 서버에 분산된 데이터를 지칭</blockquote><ul><li>레코드별로 존재하지만 스키마가 존재하지 않음</li><li>구조화된 데이터나 비구조화된 데이터 모두 지원</li></ul><h4>DataFrame과 Dataset</h4><blockquote>RDD위에 만들어지는 RDD와는 달리 필드 정보를 갖고 있음 (테이블)</blockquote><ul><li>PySpark에서는 DataFrame을 사용</li><li>Dataset은 타입 정보가 존재하며 컴파일 언어에서 사용가능 (Java, Scala)</li></ul><h4>RDD → DataFrame</h4><blockquote>성능 측면에서 긍정적</blockquote><ul><li><strong>Catalyst Optimizer의 활용</strong>:<br>Spark의 <strong>Catalyst Optimizer</strong>가 쿼리 계획을 최적화하고, 불필요한 연산을 제거하며, 효율적인 실행 계획을 수립할 수 있음</li><li><strong>Project Tungsten</strong>:<br>DataFrame은 메모리 관리와 CPU 효율성을 높이는 <strong>Project Tungsten</strong> 실행 엔진의 혜택을 받으며, 바이너리 포맷(Tungsten Binary Format)으로 데이터를 효율적으로 저장하고 처리</li></ul><p><em>RDD에서 DataFrame으로 변환하는 과정 자체에 </em><strong><em>약간의 오버헤드</em></strong><em>가 발생할 수는 있지만, 이후 DataFrame을 통한 처리 과정에서 얻는 </em><strong><em>최적화 이점</em></strong><em>이 훨씬 크기 때문에 </em><strong><em>전체 성능은 일반적으로 향상</em></strong></p><h4>DataFrame → RDD</h4><blockquote>성능 측면에서 저하될 가능성이 높음</blockquote><ul><li><strong>최적화 손실</strong>:<br>DataFrame을 RDD로 변환하는 순간, <strong>Catalyst Optimizer</strong>의 최적화 혜택을 상실</li><li><strong>직렬화/역직렬화 오버헤드</strong>:<br><em>DataFrame은 내부적으로 효율적인 이진 형식(InternalRow)으로 데이터를 관리하지만, RDD의 연산은 일반적으로 JVM 객체(Scala/Java) 또는 Python 객체를 사용.</em><br>→ 내부 이진 형식 데이터를 <strong>일반 객체로 매핑</strong>하는 작업이 필요하며, 이는 <strong>직렬화/역직렬화 오버헤드</strong></li></ul><p>Spark의 고수준 API(DataFrame, Dataset)에서 제공하지 않는 <strong>매우 세밀한 물리적 데이터 배치 제어</strong>가 필요할 때 DataFreame을 RDD로 변경</p><h3>Spark 프로그램 구조</h3><blockquote>Spark 프로그램의 시작은 SparkSession을 만드는 것</blockquote><ul><li><strong>SparkSession:</strong> Spark Cluster와 통신, <em>Singleton 객체</em></li></ul><p><a href="https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/spark_session.html">Spark Session - PySpark 4.0.1 documentation</a></p><h4>Spark Session 환경 변수</h4><ul><li><strong>Executor 별 메모리:<br></strong>spark.executor.memory (default : 1G)</li><li><strong>Executor 별 CPU 수:<br></strong>spark.executor.cores (YARN’s default : 1)</li><li><strong>Driver 메모리:<br></strong>spark.driver.memory (default : 1G)</li><li><strong>Shuffle Write 후 Partition 수:<br></strong>spark.sql.shuffle.partitions (default : 200)</li></ul><p><strong>충돌 시 우선순위는 아래일수록 높음 (4번에 설정한 값이 덮어쓰기 됨)</strong></p><ol><li><strong>환경 변수</strong> (Spark Cluster Admin이 관리)</li><li><strong>$SPARK_HOME/conf/spark_defaults.conf</strong> (Spark Cluster Admin이 관리)</li><li><strong>spark-submit 명령의 커맨드라인 파라미터</strong></li><li><strong>SparkSession 만들 때 지정</strong></li></ol><h4>전체적인 플로우</h4><ol><li>Spark Session을 만들기</li><li>입력 데이터 로딩 (Input)</li><li>데이터 조작 작업 (DataFrame API, SparkSQL 사용)</li><li>최종 결과 저장 (Output)</li></ol><h3>PySpark 설치</h3><blockquote>Local 환경에서 테스트할 경우 pip을 사용해서 간단하게 설치할 수 있음</blockquote><pre>$ pip install pyspark==3.5.1</pre><pre>spark = SparkSession.builder\<br>        .appName(&quot;spark_app&quot;)\<br>        .master(&quot;local[*]&quot;)\<br>        .getOrCreate()<br><br>spark.version</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9236d68a7dab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>