<?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 Parth Mistry on Medium]]></title>
        <description><![CDATA[Stories by Parth Mistry on Medium]]></description>
        <link>https://medium.com/@parthmistry241?source=rss-e3daf5784f1e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ccFRU0h-ptnEvG8DksdZFg.png</url>
            <title>Stories by Parth Mistry on Medium</title>
            <link>https://medium.com/@parthmistry241?source=rss-e3daf5784f1e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:35:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@parthmistry241/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[Physical Cores beat Hyper-Threads? Benchmarking the vCPU Illusion]]></title>
            <link>https://parthmistry241.medium.com/physical-cores-beat-hyper-threads-benchmarking-the-vcpu-illusion-86bb2679cb10?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/86bb2679cb10</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Wed, 06 May 2026 04:41:26 GMT</pubDate>
            <atom:updated>2026-05-06T04:41:26.518Z</atom:updated>
            <content:encoded><![CDATA[<p>In the Cloud, VM instance selection is usually done by comparing instance family, number of vCPUs, memory size, hourly cost etc. It is easy to assume that two instance types with the same number of <strong>vCPUs</strong> should provide roughly similar compute performance. However compute performance depends on subtle difference - whether <strong>vCPUs</strong> are backed by <strong>hyper-threads </strong>or <strong>dedicated physical cores</strong>.</p><p>For example if we compare AWS EC2 instances <strong>m7i.xlarge</strong> and <strong>m7a.xlarge</strong> on high level -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZiN-53zk-MMIQS2YgqZ7mQ.png" /></figure><p>Both provides same number of <strong>vCPUs</strong> and <strong>RAM</strong>. Hourly cost difference is roughly <strong>15% higher</strong> for <strong>m7a</strong> family of instances compared to <strong>m7i</strong> family of instances. However in the case of <strong>m7i</strong> family of instances - 4 vCPUs are backed by 2 physical cores (2 threads per core), where in the case of <strong>m7a</strong> family of instances - 4 vCPUs are backed by 4 dedicated physical cores (1 thread per core) which provides far more compute power than <strong>m7i</strong> instances.</p><h3>But why this difference matters?</h3><p>With 4 vCPUs backed by 2 physical cores - each physical core runs 2 hyper-threads (HT), this is also known as simultaneous multi-threading (SMT). The OS sees 4 schedulable CPUs, but pairs of threads share the same core resources such as execution units, cache, and memory pipeline.</p><p>With 4 vCPUs backed by 4 physical cores, each vCPU maps to its own physical core. Threads get dedicated core resources and CPU-bound workloads can run with much less internal contention.</p><p>The value of hyper-threads lies in their ability to maintain throughput; when one thread hits a bottleneck like memory latency, its sibling thread steps in to utilize the vacant CPU core resources.</p><p>But for heavy CPU-bound workloads where all threads actively need execution resources, VM with 4 physical cores usually outperform VM with 2 cores with 4 hyper-threads due to 2x execution resources are available.</p><p>For the purpose of this post, I will compare performance of <strong>m7i.xlarge</strong> and <strong>m7a.xlarge</strong> instances using different types of workloads such as Regex based log analyzer, data-analytics with Polars and ML Training with FAISS KMeans clustering. The goal is not to declare one instance family is universally better than the other, but to understand when additional physical cores can make a large difference for certain type of CPU-bound workloads. All sample code reference used in this post is available in repository <a href="https://github.com/parthmistry/ht-performance">ht-performance</a>.</p><h3>Assessing performance with sysbench</h3><p>Before we jump to real-world like workloads, Let’s observe CPU performance with sysbench tool. It checks the CPU performance by calculating prime numbers up to a specified value. Since this is a purely computational task, it measures the raw processing speed and the efficiency of the system’s multi-threading. Since we are having <strong>4 vCPUs</strong> we will test with <strong>4 threads</strong> -</p><pre>sysbench cpu --cpu-max-prime=20000 --threads=4 --time=30 run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*aSfEEFe41bmTpMvvwnsG9Q.png" /></figure><p>With same benchmark compute code running on both machines with same <strong>4 vCPUs </strong>- This CPU-bound task runs <strong>~3x</strong> faster on <strong>m7a</strong> family instance.</p><h3>Analyzing multi-threaded scalability</h3><p>To evaluate performance impact of increasing concurrency on CPU-bound workloads, I developed a synthetic C++ benchmark. This application simulates intensive string-processing tasks to saturate CPU resources, allowing for a controlled observation of how execution latency scales under varying thread counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*z_Nx_K_mrh8aypn3XIpg6A.png" /></figure><p>For <strong>m7i.xlarge</strong> instance - data highlights a clear correlation between thread concurrency and execution latency. At a single thread, the system maintains a baseline latency of approximately <strong>~70 ms</strong>. Moving to two concurrent threads demonstrates excellent parallel efficiency, as the total workload doubles while the execution time remains virtually unchanged. However, since this instance has only <strong>2 physical cores</strong> - a performance inflection point is reached at three threads, where latency increases by roughly <strong>64%</strong>, and further degrades to <strong>~138 ms</strong> at four threads. The doubling of latency at four threads suggests the contention for shared CPU resources.</p><p>For <strong>m7a.xlarge</strong> instance - there are <strong>4 physical cores</strong> and latency remains unchanged for up to 4 threads. Since there are same number of physical cores as number of concurrent threads, there is no CPU resource contention and all threads run without any observable performance degradation.</p><h3>Performance with real-world workloads</h3><p>To analyze head-to-head performance difference between <strong>m7i.xlarge</strong> and <strong>m7a.xlarge</strong> - I prepared few example scenarios -</p><p><strong>Log Analyzer</strong> - Java application that processes 8 GB log files in parallel<br><strong>Data Analytics</strong> - Python application powered by Polars library that analyzes 200 million synthetic customer order data<br><strong>ML Training</strong> - Train FAISS KMeans model on 2 million synthetic training samples</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPL7MhK0setIkFEyGuAZng.png" /></figure><p>A few takeaways are worth highlighting:<br><strong>ML Training</strong> is the standout. The <strong>m7a</strong> is <strong>2.91x</strong> faster. The performance-per-dollar advantage is <strong>+153%</strong>, meaning the <strong>15%</strong> price premium is essentially noise compared to the compute gain.</p><p><strong>Log Analyzer</strong> and <strong>Data Analytics</strong> are more moderate <strong>~1.6x</strong>, likely because those workloads have more <strong>I/O</strong> and <strong>memory-bound</strong> phases where raw compute performance gains are partially masked.</p><p><strong>Cost per run</strong> tells a more useful story than hourly pricing. At first glance, <strong>m7i.xlarge</strong> looks cheaper because it costs around <strong>$0.20/hour</strong> compared to <strong>$0.23/hour </strong>for <strong>m7a.xlarge</strong>. But once runtime is included, <strong>m7a.xlarge</strong> becomes cheaper per completed job in every benchmark. Across these three workloads, total runtime dropped from <strong>273.85</strong> seconds to <strong>140.64</strong> seconds, and estimated compute cost dropped from around <strong>$0.0152</strong> to <strong>$0.0090</strong> per run.</p><p>These numbers should not be treated as universal AWS performance claims. They represent my benchmark setup, input sizes, libraries, runtime configuration, and the specific instances I received during testing. Specifically <strong>m7i.xlarge</strong> EC2 performance can vary depending turbo behavior where it supports <strong>3.2 GHz</strong> basline all-core turbo frequency with max core turbo frequency of <strong>3.8 GHz</strong>. These turbo frequency keeps changing based on thermal state of the VM.</p><p>However, even with turbo variability, one architectural difference remains important: on <strong>m7i.xlarge</strong>, 4 vCPUs are backed by 2 physical cores with hyper-threading, while <strong>m7a.xlarge</strong> provides 4 physical cores. When CPU-bound workloads run across hyper-threads, sibling threads share execution resources on the same physical core. That resource contention becomes visible when the workload is able to keep all vCPUs busy. When workload is running on <strong>hyper-threads</strong>, CPU-bound tasks will face resource contention and won’t match performance where <strong>dedicated physical cores</strong> are present.</p><h3>Conclusion</h3><p>For batch compute workloads that can keep all cores busy, the cheaper hourly instance is not always the cheaper compute choice. In this test, <strong>m7a.xlarge</strong> cost <strong>15%</strong> more per hour, but delivered much faster completion time and lower cost per run.</p><p>The biggest lesson from this comparison is not simply that <strong>m7a.xlarge</strong> is faster. The real lesson is that <strong>4 vCPUs</strong> does not always mean the same thing across instance families. When those vCPUs map to <strong>dedicated physical cores</strong> instead of <strong>hyper-threads</strong>, CPU-bound workloads can behave very differently.</p><p>This is not specific to <strong>AWS</strong>. The same principle applies on other cloud platforms such as <strong>Azure</strong> and <strong>Google Cloud</strong> as well. Whenever an instance exposes vCPUs backed by hyper-threading, 2 vCPUs may be sharing execution resources on the same physical core. For workloads that are heavily parallel and CPU-bound, that distinction can directly affect runtime, throughput, and cost per completed job.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86bb2679cb10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuning linux network stack - with examples - Part 3]]></title>
            <link>https://parthmistry241.medium.com/tuning-linux-network-stack-with-examples-part-3-a7e019e4d95c?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7e019e4d95c</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[iperf3]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[iperf]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 05:56:26 GMT</pubDate>
            <atom:updated>2025-07-20T05:56:26.033Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve built a blazing-fast web application with a high-performance language/framework using Java, Go, or Rust. Load testing shows your application is scaling well with a large number of concurrent users and delivering content with ultra high speed. It’s deployed in a region geographically close to target user base, ensuring minimal latency. Survey shows large portion of target audience is already on high-bandwidth internet connections, and you’ve already tuned the Linux network stack to support thousands of concurrent connections (as covered in <a href="https://parthmistry241.medium.com/tuning-linux-network-stack-with-examples-part-1-3a3307b7adc9">[Part 1]</a>), with buffer sizes optimized for max throughput (see <a href="https://parthmistry241.medium.com/tuning-linux-network-stack-with-examples-part-2-6ff94330b7b6">[Part 2]</a>). Everything is perfect - yet users are still reporting slowness when downloading large files, continuously streaming media, or interacting with WebSocket-powered interfaces. What might be the root cause of this slowness?</p><p>Well, the real-world networks are messier than the networks in a cloud environments where performance tests might have been executed. Real users connect over unpredictable networks such as shared Wi-Fi, mobile data etc with varying bandwidths and reliability. These networks introduce latency, jitter, and packet loss that our servers must gracefully handle. Identifying real issue that might be causing slowness would be complicated. However we can first verify which congestion control algorithm our servers are using to deliver content.</p><p>By default many linux distributions are using cubic congestion control algorithm, which is good for general-purpose usage such as typical user computers as well as servers delivering content within stable networks like cloud/data center networks. But there is yet another modern congestion control algorithm BBR(Bottleneck Bandwidth and Round-trip propagation time).</p><p>In this post, we’ll see how switching to modern BBR congestion control algorithm can dramatically improve user experience in the real-world by efficiently delivering content over public networks. To show effect of cubic vs BBR congestion control algorithms, I am going to test different scenarios over different artificially simulated network conditions. I am going to use 2 AWS EC2 instances (in a same VPC). In each scenario - on a client host, I will simulate different network conditions using tc (traffc control) linux CLI utility which helps implementing various traffic shaping strategies. On a server host - I will just switch congestion control algorithm and observe the effect.</p><p>To view current congestion control algorithm on server, we can use following command -</p><pre>sysctl net.ipv4.tcp_congestion_control</pre><p>To switch congestion control algorithm on server, we can use following commands -</p><pre># To switch to cubic<br>sudo sysctl -w net.ipv4.tcp_congestion_control=cubic<br>sudo sysctl -p<br><br># To switch to BBR<br>sudo sysctl -w net.ipv4.tcp_congestion_control=bbr<br>sudo sysctl -p</pre><p>In all scenarios I am using following commands to observe network performance -</p><pre># On server<br>iperf3 -s<br><br># On client<br>iperf3 -R -c SERVER_IP -t 60 -P 4</pre><p><strong>Scenario 1 - Default network performance</strong></p><p>In this scenario, we will see effect of different congestion control algorithms in default network condition in AWS cloud allowing 10 Gbps bandwidth across EC2 hosts. Since the network is very stable we can see iperf3 test report shows close to optimal download speed on client with both congestion control algorithms -</p><ul><li><strong>With cubic -</strong><br><strong>Bitrate:</strong> 9.94 Gbits/sec<br><strong>Retransmissions:</strong> 0</li><li><strong>With BBR -</strong><br><strong>Bitrate:</strong> 9.92 Gbits/sec<br><strong>Retransmissions:</strong> 0</li></ul><p>As we can see in ideal lossless network with very low latencies and jitters - cubic congestion control algorithm performs slightly better than BBR.</p><p><strong>Scenario 2 - Simulating ingress traffic delivery latency and packet loss</strong></p><p>In this scenario, I will add artificial latency and packet loss network condition on client host for ingress traffic flow. We can do that using following command on client host -</p><pre>sudo ip link add ifb0 type ifb<br>sudo ip link set ifb0 up<br><br>sudo tc qdisc add dev ens5 handle ffff: ingress<br><br>sudo tc filter add dev ens5 parent ffff: \<br>  protocol ip u32 match u32 0 0 \<br>  action mirred egress redirect dev ifb0<br><br>sudo tc qdisc add dev ifb0 root \<br>  netem delay 80ms 20ms distribution normal loss 2%</pre><p>But how do we know if this setup is properly delaying ingress data packets and adding artificial latency which we just configured?</p><p>Simplest test to check this is with ping CLI utility. In normal condition, we will observe ping timing is very small and consistent -</p><pre>64 bytes from 8.8.8.8: icmp_seq=787 ttl=116 time=1.38 ms<br>64 bytes from 8.8.8.8: icmp_seq=788 ttl=116 time=1.31 ms<br>64 bytes from 8.8.8.8: icmp_seq=789 ttl=116 time=1.31 ms<br>64 bytes from 8.8.8.8: icmp_seq=790 ttl=116 time=1.35 ms<br>64 bytes from 8.8.8.8: icmp_seq=791 ttl=116 time=1.31 ms<br>64 bytes from 8.8.8.8: icmp_seq=792 ttl=116 time=1.30 ms<br>64 bytes from 8.8.8.8: icmp_seq=793 ttl=116 time=1.32 ms<br>64 bytes from 8.8.8.8: icmp_seq=794 ttl=116 time=1.31 ms<br>64 bytes from 8.8.8.8: icmp_seq=795 ttl=116 time=1.32 ms</pre><p>However with added artificial network condition, we can see ping network round-trip latency is high and there is random jitter -</p><pre>64 bytes from 8.8.8.8: icmp_seq=215 ttl=117 time=83.7 ms<br>64 bytes from 8.8.8.8: icmp_seq=216 ttl=117 time=38.1 ms<br>64 bytes from 8.8.8.8: icmp_seq=217 ttl=117 time=75.9 ms<br>64 bytes from 8.8.8.8: icmp_seq=218 ttl=117 time=117 ms<br>64 bytes from 8.8.8.8: icmp_seq=220 ttl=117 time=107 ms<br>64 bytes from 8.8.8.8: icmp_seq=221 ttl=117 time=79.3 ms<br>64 bytes from 8.8.8.8: icmp_seq=222 ttl=117 time=69.0 ms<br>64 bytes from 8.8.8.8: icmp_seq=223 ttl=117 time=110 ms</pre><p>Let’s observe network performance of different congestion control algorithms in this high bandwidth, high latency and lossy network -</p><ul><li><strong>With cubic -</strong><br><strong>Bitrate:</strong> 24.7 Mbits/sec<br><strong>Retransmissions:</strong> 1086<br><strong>Total Transfer:</strong> 177 MBytes</li><li><strong>With BBR -</strong><br><strong>Bitrate:</strong> 103 Mbits/sec<br><strong>Retransmissions:</strong> 89154<br><strong>Total Transfer:</strong> 740 MBytes</li></ul><p>As we can see by just switching congestion control algorithm on server host to BBR, server is able to transfer significant amount of more data to client at much higher bitrate accommodating with lossy network conditions.</p><p>For a quick side-by-side view, here’s a comparison table -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkARS2V6eRKd4RK4nwHQRA.png" /></figure><p><strong>Scenario 3 - Simulating Bufferbloat</strong></p><p>Bufferbloat is a condition where excessive buffering in network devices (like routers, switches, or other network interfaces on network path) causes high latency and jitter, especially during periods of high network usage. Bufferbloat happens when packets sit too long in an oversized queues (without dropping), increasing delay for interactive traffic like websockets, video calls, gaming, or VoIP.</p><p>Bufferbloat can produce unpredictable network performance behaviors during high network usage. For simple illustrative example in home network - if 1 user starts downloading large file and the other user is on a video call, and if bufferbloat condition happens due to all available ingress bandwidth utilization and excessive network device packet queue, then the other user will experience sluggish/choppy video call due to the video call’s packets being delayed or dropped in the overstuffed buffer.</p><p>Many times when bufferbloat happen, speed test will show good bandwidth available but interactive network traffic like gaming or video calls will still perform poorly because speed tests primarily measure throughput, not latency or packet loss, which are the key metrics affected by bufferbloat.</p><p>To simulate bufferbloat we can execute following command on client host -</p><pre>sudo ip link add ifb0 type ifb<br>sudo ip link set ifb0 up<br><br>sudo tc qdisc add dev ens5 handle ffff: ingress<br><br>sudo tc filter add dev ens5 parent ffff: \<br>  protocol ip u32 match u32 0 0 \<br>  action mirred egress redirect dev ifb0<br><br>sudo tc qdisc add dev ifb0 root handle 1: htb default 10 r2q 100<br>sudo tc class add dev ifb0 parent 1: classid 1:10 htb rate 100mbit ceil 100mbit<br>sudo tc qdisc add dev ifb0 parent 1:10 handle 10: bfifo limit 10mb</pre><p>Let’s observe ping timing after this ingress bufferbloat setup -</p><pre>64 bytes from 8.8.8.8: icmp_seq=171 ttl=117 time=1.07 ms<br>64 bytes from 8.8.8.8: icmp_seq=172 ttl=117 time=1.08 ms<br>64 bytes from 8.8.8.8: icmp_seq=173 ttl=117 time=1.08 ms<br>64 bytes from 8.8.8.8: icmp_seq=174 ttl=117 time=1.08 ms<br>64 bytes from 8.8.8.8: icmp_seq=175 ttl=117 time=1.08 ms<br>64 bytes from 8.8.8.8: icmp_seq=176 ttl=117 time=1.41 ms<br>64 bytes from 8.8.8.8: icmp_seq=177 ttl=117 time=1.07 ms<br>64 bytes from 8.8.8.8: icmp_seq=178 ttl=117 time=1.07 ms</pre><p>It is showing consistent low latency round-trip durations without much jitter when network is idle. Let’s run network performance test with cubic congestion control algorithm</p><ul><li><strong>Bitrate:</strong> 98.3 Mbits/sec<br><strong>Retransmissions:</strong> 645<br><strong>Total Transfer:</strong> 703 MBytes<br><strong>Average Packet Backlog:</strong> 631<br><strong>Average Packet Backlog Size:</strong> 9.2 MB</li></ul><p>Packet backlog can be observed during the tests by executing and monitoring output of following command -</p><pre>watch -n1 &#39;tc -s qdisc show dev ifb0&#39;</pre><p>We can see large amount of packet backlog is accumulated. If any new packet arrives it will have to wait for all prior packets in a queue to be consumed before current packet’s turn come. This will increase latency for interactive traffic. If we observe latency in ping (which is kind of interactive traffic), we will see each ping is delayed by about 700 millis which was usually completing in ~1 millis in idle network -</p><pre>64 bytes from 8.8.8.8: icmp_seq=238 ttl=117 time=781 ms<br>64 bytes from 8.8.8.8: icmp_seq=239 ttl=117 time=839 ms<br>64 bytes from 8.8.8.8: icmp_seq=240 ttl=117 time=551 ms<br>64 bytes from 8.8.8.8: icmp_seq=241 ttl=117 time=637 ms<br>64 bytes from 8.8.8.8: icmp_seq=242 ttl=117 time=692 ms<br>64 bytes from 8.8.8.8: icmp_seq=243 ttl=117 time=734 ms<br>64 bytes from 8.8.8.8: icmp_seq=244 ttl=117 time=756 ms<br>64 bytes from 8.8.8.8: icmp_seq=245 ttl=117 time=771 ms</pre><p>Let’s see how network behaves when we are using BBR congestion control algorithm on our server -</p><ul><li><strong>Bitrate:</strong> 99.2 Mbits/sec<br><strong>Retransmissions:</strong> 4<br><strong>Total Transfer:</strong> 710 MBytes<br><strong>Average Packet Backlog:</strong> 38<br><strong>Average Packet Backlog Size:</strong> 0.11 MB</li></ul><p>Since bandwidth is limited to 100 Mbps, with BBRcongestion control algorithm - server is able to send similar amount of data to the client with almost same bitrate as with cubic congestion control algorithm. However as we can see there is very low packet backlog. There is no huge queue build up of pending packets in a queue. Server continuously observe and adopt to number of packets which can be sent to this congested network and will not overflood network similar to cubic congestion control algorithm was doing. Since there is no huge queue build up, interactive traffic will experience much smoother experience with BBR compared to cubic. If we observe latency in ping, we will see each ping is delayed by about 40 millis only -</p><pre>64 bytes from 8.8.8.8: icmp_seq=360 ttl=117 time=43.0 ms<br>64 bytes from 8.8.8.8: icmp_seq=361 ttl=117 time=40.9 ms<br>64 bytes from 8.8.8.8: icmp_seq=362 ttl=117 time=48.3 ms<br>64 bytes from 8.8.8.8: icmp_seq=363 ttl=117 time=43.7 ms<br>64 bytes from 8.8.8.8: icmp_seq=364 ttl=117 time=41.5 ms<br>64 bytes from 8.8.8.8: icmp_seq=365 ttl=117 time=12.2 ms<br>64 bytes from 8.8.8.8: icmp_seq=366 ttl=117 time=63.1 ms<br>64 bytes from 8.8.8.8: icmp_seq=367 ttl=117 time=61.6 ms</pre><p>For a quick side-by-side view, here’s a comparison table -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOREvU-LS0CCu6-jjESaWw.png" /></figure><p><strong>Summary</strong><br>In essence, while cubic works well in stable, predictable network environments, BBR is a more advanced congestion control algorithm built for the realities of the public internet. It significantly enhances user experience by adeptly handling fluctuating bandwidths, latency, and packet loss. BBR achieves this by consistently and efficiently delivering data packets without overwhelming the network, resulting in a much smoother and more responsive experience for your application’s users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7e019e4d95c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delta Tables and Deletion Vectors]]></title>
            <link>https://parthmistry241.medium.com/delta-tables-and-deletion-vectors-70b7d8028190?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b7d8028190</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 06:09:57 GMT</pubDate>
            <atom:updated>2024-12-17T09:45:26.729Z</atom:updated>
            <content:encoded><![CDATA[<p>This post builds on my previous post, <a href="https://parthmistry241.medium.com/performing-scd-2-merge-over-a-billion-records-table-with-standalone-local-spark-1e180d87769f">Performing SCD-2 merge over a Billion Records Table with Standalone Local Spark</a>, which demonstrates the efficiency of executing an SCD-2 merge job using a Standalone Spark on a billion records table. However, in the worst-case scenario, the execution time can stretch to <strong>47 minutes</strong>, and the storage size <strong>doubles</strong> after the merge job execution. DeltaLake now offers <strong>Deletion Vectors</strong> feature that overcomes these downsides. In this post, we will enable deletion vectors feature for a <strong>delta</strong> table and observe impact of it on scenarios similar to those discussed in the previous post.</p><p>Deletion vectors are a storage optimization feature that you can enable on <strong>delta</strong> tables. By default, when a single row in a data file is deleted, the entire Parquet file containing the record must be rewritten. With deletion vectors enabled for the table, <strong>DELETE</strong>, <strong>UPDATE</strong>, and <strong>MERGE</strong> operations use deletion vectors to mark existing rows as removed or changed without rewriting the Parquet file. Subsequent reads on the table resolve the current table state by applying the deletions indicated by deletion vectors to the most recent table version.</p><p>We will define <strong>delta</strong> dimension table representing dummy products related data. For each example in this post we will assume -</p><ol><li><strong>products</strong> <strong>delta</strong> table having <strong>1 billion</strong> dummy product records. Table is <strong>Z-Order</strong> optimized by <strong>id</strong> column and compacted with max <strong>2 million</strong> records per parquet file. This table is also vacuumed to retain no historical changes. Deletion vectors feature is enabled for this table. Storage size of this optimized <strong>products</strong> delta table is <strong>28.1 GB</strong></li><li><strong>product_updates</strong> <strong>delta</strong> table having <strong>1 million</strong> dummy product records that represents <strong>new</strong> and/or <strong>updated</strong> records</li><li><strong>products</strong> and <strong>product_updates</strong> tables have <strong>10 data columns </strong>and additional <strong>3 meta columns</strong> that captures effective dates and current record flag values</li><li>All data is stored in <strong>AWS S3</strong> bucket</li></ol><p>For different examples in this post, we will see how much time a spark job needs to perform <strong>SCD-2</strong> merge operation when there are <strong>1 billion</strong> existing table records and <strong>1 million</strong> source records and also Delection Vectors enabled for target table. I will be using open-source standalone <strong>Apache Spark</strong> installed on <strong>AWS EC2</strong> instance <strong>(c6gd.2xlarge, 8 Core 16 GB RAM)</strong>. Source code for generating dummy product records, optimizing table, spark job with SCD-2 merge operation and instructions on how to run them is located at <a href="https://github.com/parthmistry/singlehost-scd2-dv"><strong>singlehost-scd2-dv</strong></a></p><p><strong>Software Stack</strong><br>Operating System — Ubuntu 22.04<br>GraalVM 22.3.1 (JDK 17.0.6)<br>Apache Spark 3.5.3<br>DeltaLake library 3.2.1</p><p><strong>Random source product records</strong></p><p>In this example - data for <strong>product_updates</strong> table has <strong>250K</strong> new records and <strong>750K</strong> updated records for which there are existing records in <strong>products</strong> table. These <strong>750K</strong> records are generated by picking random identifiers (between <strong>1</strong> to <strong>1 billion</strong>) for product record <strong>id</strong> column</p><p>Running spark job with <strong>SCD-2</strong> merge operation takes <strong>33 minutes</strong> of time. Remember that parquet files are immutable and even if we want to change a single record’s value (in our case effective dates and current record flag values for existing records) we need to clone whole parquet file with updated values in respective columns and re-write new parquet file. However with deletion vectors feature enabled - DeltaLake will just maintain separate metadata to mark existing records deleted and write new parquet file consisting of these updated records. In this example - <strong>750K</strong> randomly picked records spans across all the data (parquet) files of <strong>products</strong> table. Which means all existing data (parquet) files (with storage size <strong>~28.1 GB</strong>) would need to be re-written with updated value - but with deletion vectors only metadata for such updated/deleted records need to be maintained and only new/update records will go in new set of parquet files. At the end of the merge operation with <strong>delta</strong> table where deletion vectors feature is enabled - <strong>products</strong> table storage size becomes close to <strong>28.2 GB</strong> and the job doesn’t need to clone all data files.</p><p><strong>New source product records</strong></p><p>In this example - data for <strong>product_updates</strong> table has <strong>1M</strong> new records only. Since all records are new, no records are going to be updated in <strong>products</strong> table. Which means no new metadata needs to be maintained for marking existing records as deleted. New records will go in new separate set of data (parquet) files. For this example - running spark job with <strong>SCD-2</strong> merge operation completes very quickly and just takes <strong>13 minutes</strong> of time.</p><p><strong>Source product records based on targeted number of files</strong></p><p>In this example - we are going to generate data for <strong>product_updates</strong> table by targeting specific number of data files from <strong>products</strong> table. Data for <strong>product_updates</strong> table has <strong>250K</strong> new records and <strong>750K</strong> updated records for which there are existing records in <strong>products</strong> table. Product <strong>id</strong> for these <strong>750K</strong> records are picked from the specific number of parquet files (from <strong>products</strong> table) which we are targeting in the specific example. If deletion vector is not enabled - those specific number of files are going to be cloned with updated/new records and spark job execution time and storage size of <strong>products</strong> table after merge will depend on number of affected files. However with deletion vectors feature, only metadata will be maintained to mark updated records in existing data files as deleted which reduces overall storage requirement and reduces overall job execution time since entire data files don’t need to be cloned. As we can see in the following table (I have also included stats from previous examples in this table. Also stats from the previous post are also included for relative comparison)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2UJPxkh4R3ZVxtMlf9P5A.png" /></figure><p><strong>Summary</strong><br>Without <strong>Deletion Vectors</strong> feature enabled in <strong>delta</strong> table — Execution time of spark job performing SCD-2 merge operation largely depends on number of affected files of a large target table. Even if there are 500 input records and those 500 records span across all files of the target table then entire table’s data files will be cloned with updated/new records and table storage size becomes roughly double at the end of merge operation. But once we enable <strong>Deletion Vectors</strong> feature in delta table — <strong>DELETE</strong>, <strong>UPDATE</strong>, and <strong>MERGE</strong> operation maintains separate metadata and just marks respective affected records as deleted. Spark job doesn’t need to spend a lot of time in cloning and writing entire existing data files where record is updated/deleted.</p><blockquote>Regardless of whether you are using Deletion Vector feature or not — it is always recommended to keep optimizing your table on preferred interval</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b7d8028190" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with memory overheads of Java Application runtime]]></title>
            <link>https://parthmistry241.medium.com/dealing-with-memory-overheads-of-java-application-runtime-da7d21b619bc?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/da7d21b619bc</guid>
            <category><![CDATA[graalvm]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 08:34:10 GMT</pubDate>
            <atom:updated>2024-04-07T08:34:10.793Z</atom:updated>
            <content:encoded><![CDATA[<p>In one of my previous story ‘<a href="https://parthmistry241.medium.com/assessing-web-application-performance-on-single-core-machine-955ae3243085">Assessing web application performance on single-core machine’</a> - I have shown how powerful modern CPUs are and how modern frameworks and toolings can efficiently utilize them. Depending upon workload, in many of the usecases - a single-core VMs or even VMs with <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html">burstable CPU characteristics</a> can be used to deploy a large-scale microservices which can handle hundreds of requests per second without any observable latencies and can offer huge savings in terms of infrastructure costs. Having said that CPUs may not be the bottleneck in typical microservices deployment, however available memory on a host might soon become constraint especially when running multiple <strong>Java</strong> based applications per VM</p><p><strong>Java</strong> application runtime usually has a lot of memory overheads other than the heap and application threads. To name few of the things for example - each <strong>JVM</strong> instance will need its own memory space for holding <strong>JIT</strong> optimized code cache, <strong>JIT</strong> compiler metadata, metaspace, garbage collector metadata, synchronization structures, symbols etc. To observe these overheads in action, I have created sample <strong>Java</strong> application with <strong>Spring Boot</strong> framework with Reactive Stack. This application has one <strong>REST API</strong> endpoint which retrieves all records from a <strong>PostgreSQL</strong> database table and returns them as <strong>JSON</strong> objects as part of response. I am using <a href="https://gatling.io/">Gatling</a> to warm-up this application and during the warm-up phase we can capture memory usage stats. Also to capture max memory usage throughout the run, I am using time linux utility. Source code for this application is located at <a href="https://github.com/parthmistry/memoryefficient-java"><strong>memoryefficient-java</strong></a></p><p><strong>Scenario 1</strong><br>Let’s start with observing memory usage with default behavior. We specify fixed bounds for <strong>Java</strong> heap memory for our sample application and run it using following command</p><pre>JAVA_OPTS=&quot;-Xms128m -Xmx128m -XX:NativeMemoryTracking=summary&quot;<br>/bin/time -v java $JAVA_OPTS -jar demo-web.jar</pre><p><strong>VM</strong> parameter -XX:NativeMemoryTracking=summary enables extra features in <strong>JVM</strong> that captures memory usages across different areas in <strong>JVM</strong>. Following command can be used to observe memory usage while gatling simulation is running</p><pre>jcmd &lt;PROCESS_ID&gt; VM.native_memory summary</pre><p>This results into output similar to following</p><pre>Native Memory Tracking:<br><br>Total: reserved=1657484KB, committed=310468KB<br>       malloc: 47564KB #217566<br>       mmap:   reserved=1609920KB, committed=262904KB<br><br>-                 Java Heap (reserved=131072KB, committed=131072KB)<br>                            (mmap: reserved=131072KB, committed=131072KB) <br> <br>-                     Class (reserved=1049752KB, committed=7192KB)<br>                            (classes #10542)<br>    ...<br>-                    Thread (reserved=65380KB, committed=2872KB)<br>                            (thread #33)<br>    ...<br>-                      Code (reserved=251196KB, committed=38664KB)<br>                            (malloc=3508KB #12991) (at peak) <br>    ...<br>-                        GC (reserved=40501KB, committed=40501KB)<br>                            (malloc=5161KB #16108) (peak=5179KB #16237) <br>    ...<br>-                 GCCardSet (reserved=42KB, committed=42KB)<br>                            (malloc=42KB #426) (peak=49KB #448) <br> ...<br>-                     Other (reserved=16533KB, committed=16533KB)<br>                            (malloc=16533KB #22) (at peak) <br> <br>-                    Symbol (reserved=15098KB, committed=15098KB)<br>                            (malloc=13907KB #117130) (at peak) <br>    ...<br>-        Shared class space (reserved=16384KB, committed=12952KB, readonly=0KB)<br>                            (mmap: reserved=16384KB, committed=12952KB) <br>    ...<br>-           Synchronization (reserved=1164KB, committed=1164KB)<br>                            (malloc=1164KB #10637) (peak=1164KB #10639) <br>    ...<br>-                 Metaspace (reserved=65742KB, committed=39758KB)<br>                            (malloc=206KB #104) (at peak) <br>    ...</pre><p>I have removed some of the details from this output to focus only on major memory areas. This application run utilizes overall <strong>~309.4 MB</strong> of memory through out the run. Our max heap size is specified as <strong>128 MB</strong>, so there is roughly <strong>~181.4 MB</strong> of extra <strong>JVM</strong> overhead for running our application</p><p><strong>Scenario 2</strong><br>Let’s first focus on garbage collector metadata related memory space. Stats in previous scenario shows there is <strong>~39.5 MB</strong> of metadata space reserved for garbage collection related tasks. By default <strong>JVM</strong> uses <strong>G1</strong> garbage collector if it finds multiple CPU cores available on a host. It is modern <strong>GC</strong> algorithm which efficiently collects garbage by utilizing multiple CPU cores and additional managed metadata about object allocation. Size for this metadata space will increase together with increase in heap size</p><p>There are many other <strong>GC</strong> algorithms available in <strong>JVM</strong> too and each will have different memory space requirement. For example we can try <strong>ParallelGC</strong> and <strong>SerialGC</strong> and see how much memory space they need for running same application</p><pre># with parallel gc<br>JAVA_OPTS=&quot;-Xms128m -Xmx128m -XX:NativeMemoryTracking=summary&quot;<br>JAVA_OPTS+=&quot; -XX:+UseParallelGC&quot;<br>/bin/time -v java $JAVA_OPTS -jar demo-web.jar<br><br># with serial gc<br>JAVA_OPTS=&quot;-Xms128m -Xmx128m -XX:NativeMemoryTracking=summary&quot;<br>JAVA_OPTS+=&quot; -XX:+UseSerialGC&quot;<br>/bin/time -v java $JAVA_OPTS -jar demo-web.jar</pre><p>Following table shows overall memory usage and observed <strong>GC</strong> overhead when using different garbage collectors for our sample application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mWuoMYDpCIZYORkQ1Zaqg.png" /></figure><p>This illustrates that choice of <strong>GC</strong> algorithm affects <strong>GC</strong> related metadata space usage and depending on usecase we can choose <strong>GC</strong> algorithm which best fits the need. Especially when heap size is small like in our sample application, a <strong>SerialGC</strong> would be sufficient as there won’t be much garbage to collect as well</p><p><strong>Scenario 3</strong><br>In this scenario we will focus on <strong>metaspace</strong> and <strong>JIT</strong> code cache. Metaspace is the memory space where class metadata like methods, fields, bytecode etc is stored. <strong>JIT</strong> code cache is the memory space where <strong>JIT</strong> compiler will put optimized code generated for native execution. Each <strong>JVM</strong> will have its own memory space reserved for these. So once <strong>JVM</strong> starts it will load class definitions into <strong>metaspace</strong> and incrementally compile frequently used code paths to optimized native instructions and put it into code cache. Upper limit for both of these memory spaces can be tuned, but there is yet another approach available</p><p>We can use ahead-of-time (<strong>AOT</strong>) compiler available as part of <strong>GraalVM JDK</strong> to generate native executable code. Since we are pre-compiling entire <strong>Java</strong> source code, resulting executable starts much faster than regular <strong>Java</strong> application and it won’t need to have <strong>JIT</strong> compiler in background to observe hot code paths and convert bytecode to native code. Now there is no need to have space for holding raw <strong>Java</strong> class metadata and there is no need to have memory space for <strong>JIT</strong> code cache. However not every library can be directly used when we go with this approach as some libraries might be heavily relying on <strong>reflections</strong> at runtime and developers may need to specify additional metadata to make those libraries work. However generally available frameworks like <strong>Spring Boot, Quarkus</strong> etc can be used without any explicit tuning</p><p>We can use following commands to generate native binary and run it (assuming <strong>JAVA_HOME, GRAALVM_HOME </strong>and <strong>PATH</strong> environment variables are properly referring to <strong>GraalVM</strong> <strong>JDK</strong>)</p><pre>./gradlew clean nativeBuild<br>/bin/time -v ./build/native/nativeCompile/demo-web -Xms128m -Xmx128m</pre><p>This time when we run our application with native binary - max memory usage hits only <strong>~134.4 MB</strong>. Which is much closer to specified max heap size and much lower than running application on <strong>JVM</strong></p><p>We may observe slight degradation in performance as there is no <strong>JIT</strong> compiler available to do aggressive inlining and other optimizations at runtime. Advanced techniques like Profile Guided Optimizations (<strong>PGO</strong>) can be used to overcome it. But even if we don’t consider <strong>PGO</strong> techniques - this trade-off of slightly degraded application performance might be worth to consider when we don’t have <strong>CPU</strong> intensive microservices and want to reduce memory overheads of <strong>JVM</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da7d21b619bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance characteristics of Python code]]></title>
            <link>https://parthmistry241.medium.com/performance-characteristics-of-python-code-98fc4807dffc?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/98fc4807dffc</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 05:13:25 GMT</pubDate>
            <atom:updated>2023-10-26T05:25:14.941Z</atom:updated>
            <content:encoded><![CDATA[<p>Python is an interpreted, object-oriented and high-level programming language with dynamic semantics. Demand of this versatile programming language is increasing rapidly and exponentially in recent years due to significant adoption across multiple industry areas like large scale data engineering, data analytics, machine learning, artificial intelligence, scientific computing, web development etc. Especially due to simple syntax and easy learning curve, language is very much beginner-friendly and professionals like data engineers, data analysts and data science experts can easily use it for years and focus on task at hand without feeling need of building code-heavy skill-set</p><p>However due to its <strong>interpreted</strong> nature, language itself is not much efficient. Stepping through each instruction in <strong>Python</strong> code and executing equivalent machine-specific native instructions results into inefficient execution of the program. To achieve efficiency in general, programs have to rely on internal/external libraries which are usually written in native programming languages like <strong>C/C++</strong> or rely on some other external tooling. For example - major parts of standard libraries are implemented in <strong>cython</strong> - so when we execute some I/O operations, serialize/deserialize JSON objects, do some operations on dictionaries, iterate through ranges etc then all heavy-lifting will be done by native code to gain overall efficiency</p><p>In this post, I will be presenting performance characteristics associated with general interpreted <strong>Python</strong> programs which manipulates some data in-memory by using <strong>standard</strong> built-in libraries. For some of the examples I will initially present a code and then gradually increase/decrease code complexity to see how that affects performance. Together with that I will also show relative performance of equivalent <strong>Java</strong> programs. Of course comparing <strong>Python</strong> code execution stats with <strong>Java</strong> code execution stats does not make sense - but it will give general idea on overhead imposed by <strong>interpreted</strong> execution in <strong>Python</strong>. Source code of the sample programs presented in this post is located in repository <a href="https://github.com/parthmistry/python-perf-characteristics"><strong>python-perf-characteristics</strong></a></p><p><strong>Software Stack</strong><br>Operating System : Ubuntu 22.04 (2 CPUs, 16 GB RAM)<br>Amazon Corretto JDK (17.0.8)<br>Anaconda3 - Python 2.11.5</p><p><strong>Range Sum Scenarios</strong><br>In this simple test I am going to iterate from <strong>1</strong> to <strong>10 million</strong> and do sum of all iteration variable values. We do <strong>20</strong> such iterations and then print average execution duration</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/range_sum_1.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/RangeSum1.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>for i in range(0, batch_size):<br>  iteration_sum += i</pre><p>Below are the stats based on execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBKsj9Cyqv8c4EBYUBqSVQ.png" /></figure><p>As we can see in this simple basic test, iterative execution in Python code is much slower than equivalent Java code executing with JIT optimized runtime. Now Let’s see effect of adding extra static integer value in the expression for each iteration</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/range_sum_2.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/RangeSum2.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>for i in range(0, batch_size):<br>  iteration_sum += (i + 5)</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOM9ILj2pAxtILira6WjwA.png" /></figure><p>So just adding one static integer value in expression resulted in additional <strong>~200 millis</strong> overhead per <strong>10 million</strong> iterations. Let’s add one more extra static integer for each iteration and see its impact on performance</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/range_sum_3.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/RangeSum3.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>for i in range(0, batch_size):<br>  iteration_sum += (i + 5 + 10)</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-YFpd6qQAp-GdvTqxXJ5A.png" /></figure><p>So there is an additional overhead due to one more extra instruction to process per iteration while executing <strong>Python</strong> code, however on the other hand <strong>JIT</strong> optimized <strong>Java</strong> code is not affected much. And what if we move static integer values outside of that one line expression and declare them as global variables ?</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/range_sum_4.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/RangeSum4.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>a = 5<br>b = 10<br><br>for i in range(0, batch_size):<br>  iteration_sum += (i + a + b)</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3i7QSCoupRPVk5SPxOOglw.png" /></figure><p>Yup, additional overhead due to indirection introduced, <strong>Python</strong> will have to iteratively process instructions and retrieve variable values and then do sum. As we can notice - with every minor change per iteration there is much sizable amount of execution duration change in overall loop execution</p><p><strong>Integer List Sum Scenarios</strong><br>This series of examples are similar to previous one but instead of doing sum directly by using iteration variables from range, we retrieve values from lists and then use it in expression. In the first test we are pre-generating <strong>2 lists</strong> with <strong>10 million</strong> integer values. Then we iterate through <strong>10 million</strong> indexes, retrieve integer values from both lists and do sum of those retrieved integer values. We do <strong>20</strong> such iterations and then print average execution duration</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/integer_list_sum_1.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/IntegerListSum1.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>for i in range(0, batch_size):<br>  value1 = list1[i]<br>  value2 = list2[i]<br>  iteration_sum += value1 + value2</pre><p>Here are the stats based on execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gi_fQPvZREIKVURrjcW70A.png" /></figure><p>Now that we know - there will be an additional overhead due to <strong>interpreted</strong> execution of <strong>user-defined</strong> code, I won’t mention such details after every example run unless I need to share some additional information. Let’s see how performance gets affected when there are <strong>3 lists</strong> with <strong>10 million</strong> integer values in each</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/integer_list_sum_2.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/IntegerListSum2.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>for i in range(0, batch_size):<br>  value1 = list1[i]<br>  value2 = list2[i]<br>  value3 = list3[i]<br>  iteration_sum += value1 + value2 + value3</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxoKYrz24oK93wRW2cOtXA.png" /></figure><p>We can also check how performance is affected when we directly calculate sum by retrieving list values in expression itself without explicit variable declaration</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/integer_list_sum_3.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/IntegerListSum3.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>for i in range(0, batch_size):<br>  iteration_sum += list1[i] + list2[i] + list3[i]</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaK9m57pDjIlyWRohTBfxg.png" /></figure><p>As we can see, just removing explicit variable declaration reduces a lot of time in execution duration in case of <strong>Python</strong></p><p>Let’s try different case where I encapsulate summation logic into a <strong>CustomMath</strong> class and in each iteration I create an instance of that class and call its method to do sum of two values retrieved from the lists</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/integer_list_sum_with_object_allocation_1.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/IntegerListSumWithObjectAllocation1.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>for i in range(0, batch_size):<br>  value1 = list1[i]<br>  value2 = list2[i]<br>  custom_math = CustomMath()<br>  iteration_sum += custom_math.do_sum(value1, value2)</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FKPVgdF6NU25SUCrMbNN6A.png" /></figure><p>Of course as per given example, it would be ideal to create an instance of a class once outside of iterations and we should just call a method on that same instance of class. Let’s see how that change affects performance</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/integer_list_sum_with_object_allocation_2.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/IntegerListSumWithObjectAllocation2.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>for i in range(0, batch_size):<br>  value1 = list1[i]<br>  value2 = list2[i]<br>  iteration_sum += custom_math.do_sum(value1, value2)</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vqTCVTLFeKvaEWel1gAkg.png" /></figure><p><strong>Integer-String Conversion Scenarios</strong><br>This test executes in 2 phases. In the first phase it iterates through <strong>1</strong> to <strong>10 million</strong> and converts all iteration variable values to string and do sum of all such string value’s length. For the second phase I am pre-generating list of string values comprising integer values from <strong>1</strong> to <strong>10 million</strong>, Then I iterate through all these string values and convert all iteration variable values to integer and do sum of all such integer values. We do <strong>20</strong> such iterations of each phase and then print average execution duration</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/integer_string_conversion.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/IntegerStringConversion.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre># code snippet for integer to string conversion<br>for i in range(0, batch_size):<br>  s = str(i)<br>  iteration_sum += len(s)<br><br><br># code snippet for string to integer conversion<br>for str_value in str_list:<br>  num = int(str_value)<br>  iteration_sum += num</pre><p>Here are the stats based on execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFkiH_O0cnzv7Om7AlVIcg.png" /></figure><p><strong>Retrieve Dictionary Values Scenario</strong><br>In this test, I am pre-generating a list with <strong>10 million</strong> random unique string values and pre-generating a dictionary with same set of string values as keys but inserting keys in randomized order. All dictionary keys refer to same static integer value <strong>1</strong> just for demonstration purpose. Then I iterate through all string values from a list and retrieve value associated with current string variable from a dictionary. If value is present then we do sum of all such retrieved integer values. There are <strong>20</strong> such iterations and then program prints average execution duration</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/map_test.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/MapTest.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>for uuid in uuid_list:<br>    map_value = uuid_map[uuid]<br>    if map_value is not None:<br>        iteration_sum += map_value</pre><p>Here are the stats based on execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEXuaJ6mnYBWVawdXw1-_w.png" /></figure><p><strong>JSON Conversion Scenarios</strong><br>This test executes in 2 phases. In the first phase it serializes <strong>1 million</strong> dictionaries to string values and keeps appending serialized string values to a list. In the second phase it deserializes <strong>1 million</strong> string values to dictionaries and keeps appending deserialized dictionaries to a list. There are <strong>20</strong> such iterations of each phase and in the end it prints average execution duration</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/json_conversion.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/JsonConversion.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre># code snippet for json serialization<br>for parsed_dict in parsed_dicts:<br>  json_str_list.append(json.dumps(parsed_dict))<br><br># code snippet for json deserialization<br>for raw_json_str in raw_json_str_list:<br>  deserialized_list.append(json.loads(raw_json_str))</pre><p>Here are the stats based on execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipZ1RCotME_Ci9x-2eOL7w.png" /></figure><p>Of course, serializing/deserializing JSON is a <strong>CPU intensive</strong> task and doing it in an interpreted way would waste lots of <strong>CPU cycles</strong>. However our <strong>Python</strong> code was able to take advantage of <strong>cython</strong> implementation of the <strong>json</strong> module and overall execution isn’t too slow. Even though serialization/deserialization is happening through <strong>native code</strong> and it is extremely fast, user defined <strong>Python</strong> code still executes in <strong>interpreted</strong> mode and overall execution time is still slower compared to <strong>Java</strong></p><p><strong>Log Analysis Scenarios</strong><br>In this series of examples, we are going to read log file line-by-line and collect some aggregations. Log file is having <strong>100 million</strong> log lines and log file size is <strong>5.4 GB</strong>. In the first example I just go through the log lines and count the number of log lines</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/log_line_count.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/LogLineCount.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>with open(log_file_path, &#39;r&#39;) as log_file:<br>    while line := log_file.readline():<br>        log_line_count += 1</pre><p>Here are the stats based on execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObdRWF8qGtGbmfeVpnKBiw.png" /></figure><p>For the second example, together with counting number of log lines I also do sum of all log lines’ length. When we read a line from a file using <strong>Python</strong> it preserves line terminator, we are stripping those line terminators as well</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/log_line_count_with_line_size_sum.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/LogLineCountWithLineSizeSum.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>with open(log_file_path, &#39;r&#39;) as log_file:<br>    while line := log_file.readline():<br>        log_line_count = log_line_count + 1<br>        line_size_sum += len(line.rstrip(&#39;\n&#39;))</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypkw0I2bdX-QL9hZ1WYg8A.png" /></figure><p>In the third example, I am locating index of ‘REQUEST on’ string value from the log line and doing substring based on located index and count occurrence of specific characters in that substring</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/log_line_substring_char_count_1.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/LogLineSubstringCharCount1.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>with open(log_file_path, &#39;r&#39;) as log_file:<br>    while line := log_file.readline():<br>        processed_line = line.rstrip(&#39;\n&#39;)<br>        request_on_index = processed_line.find(&quot;REQUEST on&quot;)<br>        if request_on_index != -1:<br>            substring = processed_line[request_on_index:]<br>            for c in substring:<br>                if c == &#39;A&#39; or c == &#39;E&#39;:<br>                    char_count += 1</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8o03yxBdOykeXZ9fLp4Uw.png" /></figure><p>Fourth example is similar to the third one but we are also converting extracted substring to uppercase before counting occurrence of specific characters</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/log_line_substring_char_count_2.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/LogLineSubstringCharCount2.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>with open(log_file_path, &#39;r&#39;) as log_file:<br>    while line := log_file.readline():<br>        processed_line = line.rstrip(&#39;\n&#39;)<br>        request_on_index = processed_line.find(&quot;REQUEST on&quot;)<br>        if request_on_index != -1:<br>            substring = processed_line[request_on_index:].upper()<br>            for c in substring:<br>                if c == &#39;A&#39; or c == &#39;E&#39;:<br>                    char_count += 1</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1rEh82utLJZBsu22sZCgQ.png" /></figure><p>In the fifth example, I am trying to match log lines with regex and count number of matching log lines</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/log_line_regex_count.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/LogLineRegexCount.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>pattern = re.compile(&quot;[\\d]+-[\\d]+-[\\d]+ [\\d]+:[\\d]+:[\\d]+\.[\\d]+ .* REQUEST on (.*)&quot;)<br><br>with open(log_file_path, &#39;r&#39;) as log_file:<br>    while line := log_file.readline():<br>        processed_line = line.rstrip(&#39;\n&#39;)<br>        result = pattern.search(processed_line)<br>        if result is not None:<br>            log_line_count += 1</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wf0nMcP7xhKjue1xP1mY7Q.png" /></figure><p>Well, matching a regex on string values is an expensive operation. Even if I test with highly optimized code written in <strong>C++</strong> or <strong>Rust</strong>, then matching regex on <strong>100 million</strong> string values takes about <strong>55+ seconds</strong>. Magically Java application can achieve the same result in <strong>~34 seconds</strong>. I believe <strong>JVM</strong>’s ability to aggressive code inlining at runtime makes code execution extremely efficient which can even beat <strong>native code</strong> execution. Considering this complexity, <strong>Python</strong> code could potentially take more than half an hour of execution time if it was <strong>interpreted</strong>. But thanks to standard library module <strong>re</strong> which takes advantage of <strong>native code</strong> via <strong>cython </strong>and execution completes in <strong>~101 seconds</strong></p><p>Next example is similar to previous one where I am trying to match log lines with regex. In addition to that if line is matching then I extract substring from regex using matched groups and counting occurrence of specific characters in that substring after converting extracted substring in uppercase</p><p>Source code: <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/python-samples/log_line_regex_with_char_count.py">Python</a> | <a href="https://github.com/parthmistry/python-perf-characteristics/blob/main/java-samples/src/main/java/posts/parthmistry/javasamples/LogLineRegexWithCharCount.java">Java</a></p><p>Following is the code snippet we are observing for performance</p><pre>pattern = re.compile(&quot;[\\d]+-[\\d]+-[\\d]+ [\\d]+:[\\d]+:[\\d]+\.[\\d]+ .* REQUEST on (.*)&quot;)<br><br>with open(log_file_path, &#39;r&#39;) as log_file:<br>    while line := log_file.readline():<br>        processed_line = line.rstrip(&#39;\n&#39;)<br>        result = pattern.search(processed_line)<br>        if result is not None:<br>            matched_group_str = result.groups()[0].upper()<br>            for c in matched_group_str:<br>                if c == &#39;A&#39; or c == &#39;E&#39;:<br>                    char_count += 1</pre><p>Here are the stats based on execution together with previous example runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYpZsWFucDSjsBJ2g_3Uyg.png" /></figure><p><strong>Summary</strong></p><p>Interpreted <strong>Python</strong> code execution is inefficient - everyone knows that. In this post I have presented some basic programming code samples which utilizes built-in facilities and modules like ranges, lists, dictionaries, json serializer/deserializer, regular expression matcher etc which are implemented in <strong>cython</strong> and takes advantage of <strong>native code</strong> to gain efficiency, but <strong>user-defined code</strong> is still executed in <strong>interpreted</strong> mode which results into overall slowness. Of course examples were simple in this post and when more <strong>user-defined code</strong> is added to fulfill actual business logic in real projects, then a lot more CPU burns in just interpreting and executing instructions</p><p>However as we can see from recent trends, <strong>Python</strong> is used heavily in many industry areas like web development, data engineering, data analysis, data science etc. Many of those usually need to deal with massive amount of data. In such cases, <strong>Python</strong> provides simple interface with easy to use/understand language to developers and data professionals and under the hood it might rely on <strong>native</strong> or <strong>external</strong> toolings to do all heavy lifting. For example -</p><ul><li>Data science toolings like <strong>numpy</strong>, <strong>scipy</strong>, <strong>scikit-learn</strong>, <strong>tensorflow</strong> etc uses <strong>native code</strong> for efficiency</li><li>There is an alternative available for <strong>pandas</strong> with highly efficient backend <strong>polars</strong> written in <strong>Rust</strong></li><li>Data engineering tool <strong>pyspark</strong> relies on external <strong>JVM</strong> where actual data gets processed</li><li><strong>HTTP/REST APIs</strong> can be deployed on <strong>serverless cloud functions</strong> which provides scalability from <strong>Zero</strong> to <strong>Planet-Scale</strong> with no maintenance overhead</li><li>Run <strong>Python</strong> programs with <strong>PyPy</strong> which includes Just-in-Time compiler to efficiently run <strong>Python</strong> code at runtime</li></ul><p><strong>P.S.</strong><br>Do share feedback in comment if you find python code samples can be improved further, any alternate ways to gain efficiency or post content appears inappropriate. I will update and re-test scenarios as soon as time permits</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98fc4807dffc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performing SCD-2 merge over a Billion Records Table with Standalone Local Spark]]></title>
            <link>https://parthmistry241.medium.com/performing-scd-2-merge-over-a-billion-records-table-with-standalone-local-spark-1e180d87769f?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e180d87769f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[delta-lake]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 04:24:39 GMT</pubDate>
            <atom:updated>2023-02-28T04:24:39.784Z</atom:updated>
            <content:encoded><![CDATA[<p>Dimensional Data Modeling and Change Data Capture (CDC) is important in every data warehouses. Kimball and his team introduced dimensional data modeling to the world in late 90s and since then it became kind of de-facto standard to structure data warehouses. One of the concept in dimensional data modeling is Slowly Changing Dimension (<strong>SCD</strong>) which defines how data should be captured in dimension table when existing record’s value(s) is updated. There are multiple techniques (<strong>SCD-0</strong> to <strong>SCD-7</strong>) available by which we can implement dimension tables and each of these techniques can be implemented depending on business use case</p><p><strong>Type-2</strong> Slowly Changing Dimension (<strong>SCD-2</strong>) aims to track whole history of changes done to the dimension table records over time. Every time record value is updated - it creates new record in dimension table and keeps values in old record same as earlier. Together with that effective dates and current record flag values are updated accordingly on new and old records. I won’t go into much detail about Type-2 slowly changing dimension as this concept is over decades old, well understood and nicely detailed information about it is covered on various sites over the internet. In big data world - modern open-source datalake storage formats like <a href="https://delta.io/"><strong>Delta</strong></a>, <a href="https://hudi.apache.org/"><strong>Hudi</strong></a> and <a href="https://iceberg.apache.org/"><strong>Iceberg</strong></a> makes it easy to implement such dimensional data table by using <strong>MERGE INTO</strong> kind of <strong>SQL</strong> statements</p><p>For the purpose of this post - I am considering <strong>delta</strong> storage format to define dimension table for dummy products related data. For each example in this post we will assume -</p><ol><li><strong>products</strong> <strong>delta</strong> table having <strong>1 billion</strong> dummy product records. Table is <strong>Z-Order</strong> optimized by <strong>id</strong> column and compacted with max <strong>2 million</strong> records per parquet file. This table is also vacuumed to retain no historical changes. Storage size of this optimized <strong>products</strong> delta table is <strong>28.1 GB</strong></li><li><strong>product_updates</strong> <strong>delta</strong> table having <strong>1 million</strong> dummy product records that represents <strong>new</strong> and/or <strong>updated</strong> records</li><li><strong>products</strong> and <strong>product_updates</strong> tables have <strong>10 data columns </strong>and additional <strong>3 meta columns</strong> that captures effective dates and current record flag values</li><li>All data is stored in <strong>AWS S3</strong> bucket</li></ol><p>For different examples in this post, we will see how much time a spark job needs to perform <strong>SCD-2</strong> merge operation when there are <strong>1 billion</strong> existing table records and <strong>1 million</strong> source records. I will be using open-source standalone <strong>Apache Spark</strong> installed on <strong>AWS EC2</strong> instance <strong>(c6gd.2xlarge, 8 Core 16 GB RAM)</strong>. Source code for generating dummy product records, optimizing table, spark job with SCD-2 merge operation and instructions on how to run them is located at <a href="https://github.com/parthmistry/singlehost-scd2"><strong>singlehost-scd2</strong></a></p><p>Purpose of this post is to check baseline performance of processing a billion records table using <strong>Apache Spark</strong> running on a <strong>single machine</strong> and simulate scenarios where job execution time varies by large margin even if same amount of source and target data is there. I have intentionally considered <strong>non-partitioned</strong> table because job execution behavior shown in this post is as applicable to multi-partition table where we run merge jobs for individual partitions and each of those partitions are having a billion records. In that sense a spark job can easily handle <strong>multi-billion</strong> records table with just <strong>single machine</strong></p><p><strong>Software Stack</strong><br>Operating System - Ubuntu 22.04<br>GraalVM 22.3.1 (JDK 17.0.6)<br>Apache Spark 3.3.2<br>DeltaLake library 2.2.0</p><p><strong>Random source product records</strong></p><p>In this example - data for <strong>product_updates</strong> table has <strong>250K</strong> new records and <strong>750K</strong> updated records for which there are existing records in <strong>products</strong> table. These <strong>750K</strong> records are generated by picking random identifiers (between <strong>1</strong> to <strong>1 billion</strong>) for product record <strong>id</strong> column</p><p>Running spark job with <strong>SCD-2</strong> merge operation takes <strong>47 minutes</strong> of time. Remember that parquet files are immutable and even if we want to change a single record’s value (in our case effective dates and current record flag values for existing records) we need to clone whole parquet file with updated values in respective columns and re-write new parquet file. In this example - <strong>750K</strong> randomly picked records spans across all the data (parquet) files of <strong>products</strong> table. Which means all existing data (parquet) files (with storage size <strong>~28.1 GB</strong>) need to be re-written with updated value together with new records. At the end of the merge operation - <strong>products</strong> table storage size becomes close to <strong>61.3 GB</strong></p><p><strong>New source product records</strong></p><p>In this example - data for <strong>product_updates</strong> table has <strong>1M</strong> new records only. Since all records are new, no records are going to be updated in <strong>products</strong> table. Which means none of the existing <strong>products</strong> table data (parquet) files are going to be cloned with updated/new record values. New records will go in new separate set of data (parquet) files. For this example - running spark job with <strong>SCD-2</strong> merge operation completes very quickly and just takes <strong>13 minutes</strong> of time</p><p><strong>Source product records based on targeted number of files</strong></p><p>As we have seen when spark job with <strong>SCD-2</strong> merge operation runs, it compares which product records from <strong>product_updates</strong> table are matching with existing data (parquet) files in <strong>products</strong> table and prepares list of files which need to be cloned by combining new/updated records. Which means only those files where <strong>product_updates</strong> table records are matching (and updated) are going to be cloned together with new combined data. To test this behavior in controlled manner we are going to generate data for <strong>product_updates</strong> table by targeting specific number of data files from <strong>products</strong> table</p><p>In this example - data for <strong>product_updates</strong> table has <strong>250K</strong> new records and <strong>750K</strong> updated records for which there are existing records in <strong>products</strong> table. Product <strong>id</strong> for the <strong>750K</strong> records are picked from the specific number of parquet files (from <strong>products</strong> table) which we are targeting in the specific example. Since only specific number of files are going to be cloned with updated/new records, spark job execution time and storage size of <strong>products</strong> table after merge will depend on number of affected files as we can see in the following table (I have also included stats from previous examples in this table)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6Vx6du8gyysptugwdj8hQ.png" /></figure><p><strong>Summary</strong><br>Execution time of spark job performing <strong>SCD-2</strong> merge operation largely depends on number of affected files of a large target table. Even if there are <strong>500</strong> input records and those <strong>500</strong> records span across all files of the target table then whole table’s data files will be <strong>cloned</strong> with updated/new records and table storage size becomes roughly double at the end of merge operation. Spark job will spend majority of the time in cloning and writing both affected and unaffected records in new set of parquet files in target table</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e180d87769f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Loom and Project Reactor - Better Together]]></title>
            <link>https://parthmistry241.medium.com/project-loom-and-project-reactor-better-together-88b1f46baf9?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b1f46baf9</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[reactor-project]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[project-loom]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 02:54:45 GMT</pubDate>
            <atom:updated>2022-12-01T03:01:38.410Z</atom:updated>
            <content:encoded><![CDATA[<p>Project Loom is now available as a preview feature as part of Java 19. It introduces virtual threads to Java platform which is a lightweight implementation of threads that is provided by the JDK rather than the OS. About one year ago I came across this <a href="https://www.youtube.com/watch?v=9si7gK94gLo&amp;t=1156s">YouTube</a> video where Brian Goetz mentions “I think Project Loom is going to kill Reactive Programming” - how ever if we broadly look at purpose of project loom (virtual threads) and reactive programming they appear to solve different set of problems. Project loom makes it possible to spawn millions of virtual threads performing I/O bound tasks within same JVM, but virtual threads are still threads and when it comes to developing complex asynchronous backpressure ready data pipeline then developers still have to code it by hand. Where reactive programming is more concerned with asynchronous data streams and the propagation of change. There are various libraries available such as <a href="https://projectreactor.io/">Project Reactor</a>, <a href="https://reactivex.io/">RxJava</a>, <a href="https://vertx.io/">Vert.x</a> etc which support reactive programming by providing rich set of operators to define complex asynchronous data processing pipeline</p><p>In this post we will see why Project Loom (virtual threads) alone might not be sufficient for building efficient data processing pipelines and how project reactor can take advantage of virtual threads</p><p><strong>Demo Scenario</strong><br>For this post, I have prepared PostgreSQL database table <strong>persons</strong> with <strong>10,000 dummy records</strong>. I have considered typical application flow where we want to query records from <strong>persons</strong> table, for each retrieved record enrich data based on external service and then print enriched person detail to the terminal. To solve this problem, I have created set of examples with different concurrency approaches to see how they could impact overall application throughput. There are few other things which I have considered across these examples in this post -</p><ul><li>Example code must not retrieve all records in memory at once. It should process all records by incrementally retrieving it. This is to ensure that our example code should still work even if table has millions of records and JVM shouldn’t run out of memory</li><li>To keep code examples simple and focused around particular concurrency approach - instead of actual external service I am using mock service object which returns dummy enriched data</li><li>For making visible impact of different concurrency approaches, I am considering amplified latencies for both database related network traffic and for mock external service which enriches person data</li><li>All traffic to database is delayed by <strong>250 millis</strong>. To make this possible on local machine - I have developed <a href="https://netty.io/">Netty</a> application <strong>delay-simulator</strong> which acts as proxy between database and example application code</li><li>Mock service returns result with predictable delay of <strong>100 - 200 millis </strong>based on person id</li><li>There must not be more than <strong>50 concurrent requests</strong> for enriching person data. This is to ensure that target service doesn’t get overloaded by lots of concurrent requests</li><li>I am considering standard <strong>PostgreSQL JDBC driver</strong> in all code examples so that database communication related code paths use consistent mechanism for retrieval of records. This helps to relatively compare code complexities involved when using <strong>virtual threads</strong> or when using abstractions defined by <strong>project reactor</strong> in respective code examples. In real project, it might be better to use <a href="https://r2dbc.io/">R2DBC</a> or <a href="https://hibernate.org/reactive/">Reactive Hibernate</a> if they are suitable for the project requirement</li></ul><p>All example approaches referred in this post and delay-simulator source code is available in <a href="https://github.com/parthmistry/loom-and-reactor">loom-and-reactor</a>. I have also prepared set of gists for a quick reference while reading through the post. Click on a link provided in approach title to open respective gist which illustrates code snippet for a particular approach (Note - I haven’t shown project specific classes as part of import statements in these gists)</p><p><strong>Approach 1 - Single threaded processing - </strong><a href="https://gist.github.com/parthmistry/f442a82c015d18c55e907db9298e4b7e"><strong>code link</strong></a></p><p>For this approach we are doing all processing in a single thread (main thread in our case). This is only example code in this post where we are not using Java virtual threads. In this imperative style of example we retrieve records from database table in batch of <strong>100 records</strong> at a time and process them one after another by iterating over JDBC result set. For each record we enrich person data by calling <strong>PersonDataService</strong> which takes about <strong>100–200 millis </strong>based on person id. Once <strong>100 records</strong> are iterated there will be network call to database (internally by result set) to fetch next batch of <strong>100 records</strong>. Due to amplified latencies as mentioned earlier, This sequential style of processing takes a lot of time and overall it takes about <strong>25.5 minutes (1533.44 seconds)</strong> to process all records in the table</p><p><strong>Approach 2 - Basic multi-threaded processing - </strong><a href="https://gist.github.com/parthmistry/c8fec997d1fbb1815428fc33fdb37edd"><strong>code link</strong></a></p><p>For this approach we retrieve records from database table in batch of <strong>100 records</strong> at a time and process them concurrently by submitting individual time-consuming enrichment task to <strong>virtual thread per task executor</strong>. This approach will create <strong>100 virtual threads</strong> for processing each submitted task but since we want no more than <strong>50 concurrent requests</strong> to enrichment service - we limit overall concurrency by using semaphore which only permits maximum of <strong>50 simultaneous tasks</strong> at any point in time. Once all <strong>100 tasks</strong> are finished we retrieve next batch of <strong>100 records</strong> from database table and repeat same process for concurrent enrichment. This small enhancement in approach makes processing dramatically faster and overall it takes about <strong>64.9 seconds</strong> to process all records in the table</p><p><strong>Approach 3 - Prefetch records together with multi-threaded processing - </strong><a href="https://gist.github.com/parthmistry/454003c10f231ce4de15a90ae553f7c9"><strong>code link</strong></a></p><p>This approach adds small enhancement on top of previous approach by fetching next batch of records while records in current batch are being processed concurrently as part of their <strong>dedicated virtual threads</strong>. Once all tasks are submitted to <strong>virtual thread per task executor</strong>, we immediately attempt to retrieve next batch of records. Once next batch of records are available we keep waiting till current set of concurrent tasks are complete and once they are complete next iteration of loop immediately submits <strong>100 </strong>concurrent enrichment tasks to <strong>virtual thread per task executor</strong>. So we spend comparatively less or no time in fetching next batch of records (depending on how fast submitted concurrent tasks are complete) and overall this approach takes about <strong>38.3 seconds</strong> to process all records in the table</p><p><strong>Approach 4 - Poll next record from processing threads and keep next 100 records ready for processing - </strong><a href="https://gist.github.com/parthmistry/68e898f4f7820bc132f23c92d6b8c91e"><strong>code link</strong></a></p><p>Prefetching next batch of records while current batch of records are being processed better utilizes resources as we have seen in previous approach. There is still scope of further enhancement in that approach. Remember we are creating <strong>100 virtual threads</strong> for each enrichment task but at any given point in time we want to limit maximum of <strong>50 concurrent request</strong> to enrichment service. We use semaphore with <strong>permit=50</strong> to enforce this limits. So out of <strong>100 tasks</strong> which are submitted together - only <strong>50 tasks</strong> will make progress and others will wait for permit from semaphore. As soon as <strong>1 task</strong> is complete it will release 1 semaphore permit and one of the waiting task can make progress. We are not submitting any new tasks until currently submitted <strong>100 tasks</strong> are complete. After 51 of the submitted tasks are complete - there will be less number of concurrent enrichment requests than what is permitted and we will have to wait till longest last task is complete before we start submitting next batch of records</p><p>Since enrichment task is time consuming and number of allowed concurrent requests are limited - it would be better if we can continuously maintain <strong>50 concurrent requests</strong> to enrichment service and try to utilize available capacity as maximum as possible. In practice there are too many ways to implement this kind of flow but I have prepared one basic implementation where there are two types of tasks - one is responsible for fetching records from database tables and other keeps processing records as soon as they are available from the first task. Here is a high level implementation notes between <strong>PersonDataRetriever</strong> task and <strong>ProcessPersonData</strong> task -</p><ol><li>There is one <strong>virtual thread</strong> running <strong>PersonDataRetriever</strong> task and it is responsible to prefetch and maintain list of <strong>100 records </strong>in memory</li><li>There are <strong>50 virtual threads</strong> running <strong>ProcessPersonData</strong> task. These tasks poll next available record from <strong>PersonDataRetriever</strong> task. Once record is available - it sends request for enrichment service and finally prints output to the terminal</li><li>When <strong>ProcessPersonData </strong>task polls next record and if next record is immediately available as part of prefetched list of <strong>100 records</strong> then next record will be immediately shared by <strong>PersonDataRetriever </strong>task. However if prefetched list of records is empty (this can happen if data processor is faster than data retriever), current polling request will be added to list of waiting tasks and it will be signaled with a record as soon as next record is available</li></ol><p>In simple terminology - there are <strong>2 tasks</strong> where one task is responsible for retrieving records from database table and other task is responsible for processing records. There is a formal contract between them that if record is immediately available then it will be shared to processing task otherwise processing task will be signaled later whenever a record is available. This approach takes about <strong>29.9 seconds</strong> to process all records in the table</p><p>As I mentioned earlier - this is not only way to implement continuous prefetching and processing but just a basic implementation. We can further add exception handling mechanisms, add generics to the tasks, improve efficiency in contract/implementation etc to make this approach more reusable, maintainable and efficient - but for the purpose of this post I have kept implementation simple</p><p><strong>Approach 5 - Use reactor to define data processing pipeline and publish records based on demand - </strong><a href="https://gist.github.com/parthmistry/1e734cce0d86c3a5164e4ccd4f906be7"><strong>code link</strong></a></p><p>One might think there is a lot of code to solve a simple problem which we have - keep prefetching records and continuously process them concurrently with <strong>50 virtual threads</strong>. But Java platform threads, virtual threads or built-in concurrency framework does not have abstractions that help composing such asynchronous data streams. Developers are in control on how to define asynchronous data processing pipeline as we saw in <strong>Approach 4</strong> previously. So we may look up to some readily available library which helps composing such asynchronous data pipeline. This is where <strong>project reactor</strong> becomes helpful. In this approach I have prepared data processing pipeline which is somewhat similar to previous approach. We want to prefetch records from database tables and feed it to data processing pipeline developed using operators defined by <strong>project reactor</strong> and by considering <strong>demand</strong> from downstream pipeline operators</p><p>In this example -<strong> PersonDataRetrieverForReactor</strong> is responsible to fetch database table records and feed them to data processing pipeline considering demand from the downstream pipeline operators. Here as we can see data retriever task’s code is a lot more simpler than what we defined in <strong>Approach 4</strong>. Considering current demand we just emit <strong>1 record</strong> at a time. Keeping track of prefetched list of records is now responsibility of reactive pipeline operators which we can declaratively define when we compose a pipeline. This approach takes about <strong>30.3 seconds</strong> to process all records in the table which is slightly more than <strong>Approach 4</strong> but code example seems a lot more simpler, maintainable and due to reduced complexities there are less chances of bugs</p><p>If we use reactive database client such as <strong>R2DBC</strong>, then we won’t even have to write class like <strong>PersonDataRetrieverForReactor</strong> which retrieves data considering demand. Since this database client itself is reactive, it will internally consider demand from downstream operators and will keep fetching more data as and when required. Here is a link for code example using such reactive database client - <a href="https://gist.github.com/parthmistry/c1e22cb638130c3f9ba81e6390b987bd"><strong>code link</strong></a>. That code example takes about <strong>30.2 seconds</strong> to process all records in the table</p><p>Some times we may need to execute blocking operation from within reactive pipeline. Project reactor provides a specialized thread pool for executing such blocking operations called <strong>bounded elastic thread pool</strong>. By default this bounded elastic thread pool is backed by 1:1 platform threads and number of threads in thread pool are limited. Now that project loom is available which can easily handle millions of virtual threads executing blocking I/O tasks - project reactor can take advantage of this by publishing all such blocking operations on a scheduler backed by <strong>virtual thread pool</strong> like -</p><pre>Schedulers.fromExecutor(<br>  Executors.newVirtualThreadPerTaskExecutor()<br>)</pre><p><strong>Summary:</strong><br>Developing complex and efficient data pipelines for processing stream of data is very much feasible but quite cumbersome to write when we only rely on <strong>virtual threads</strong>. In this post I mainly focused on a basic example with streaming source of data but if pipeline is long and having bunch of complex intermediate asynchronous tasks then we may need to rely on libraries which provides reactive programming facilities such as <strong>project reactor </strong>- until Java itself has built-in APIs with such capability. On the other side - <strong>project reactor</strong> now can take advantage of <strong>virtual threads</strong> by publishing all blocking operations from data processing pipeline to a scheduler backed by <strong>virtual thread pool</strong></p><p><strong>Reference :</strong> <a href="https://www.youtube.com/watch?v=YwG04UZP2a0">Project Loom — A Friend or Foe of Reactive? — Oleh Dokuka, VMware &amp; Andrii Rodionov</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b1f46baf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Assessing web application performance on single-core machine]]></title>
            <link>https://parthmistry241.medium.com/assessing-web-application-performance-on-single-core-machine-955ae3243085?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/955ae3243085</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[gatling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Mon, 10 Oct 2022 02:04:01 GMT</pubDate>
            <atom:updated>2022-10-10T04:34:18.215Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern web applications developed on top of non-blocking I/O facilities can easily serve tens of thousands of concurrent requests per host (with moderate sized hardware). Together with horizontal scalability, scenarios where applications serve millions of concurrent requests are not new. Each web application instance being deployed is supposed to handle different amount of concurrent load depending on use cases and it needs to be deployed on machine with suitable hardware. Sometimes these applications are deployed on predetermined over-sized hardware which could result into unnecessary infrastructure usage cost. Assessing optimal hardware size for running an application could be important in such cases. I often wonder how much concurrent load a single-core machine can handle and hence writing this post based on my experiments</p><p><strong>Test Scenario</strong><br>For assessing baseline performance on single-core machine, I am taking example of basic demo web application having RESTful service endpoint. Usually these kind of applications don’t perform CPU-intensive calculations, rather they rely on external data sources and/or other applications to exchange data and perform some in-memory processing on data as per the required use cases. I have developed 2 applications (one with <strong>Java</strong> and another with <strong>Rust</strong>) having one RESTful service endpoint <strong>/api/demo</strong>. These applications are deployed on a host with single-core CPU. To serve a single request - implementation in this endpoint makes 8 different sequential REST API calls to another application running on remote host (to mimic requests to external systems). This another application is running on host with sufficient hardware to handle any number of concurrent requests which could potentially come from demo application running on single-core host. I have used <a href="https://gatling.io/"><strong>Gatling</strong></a> application as load-testing tool which runs various load testing scenarios from yet another host. All 3 hosts are running as part of same virtual network in the cloud. Following diagram represents how applications are deployed across hosts -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDm9n1KULAc--bWTw-pvhA.png" /></figure><p><strong>Software Stack</strong><br>Operating System : Ubuntu 22.04<br>Amazon Corretto JDK (17.0.4)<br>Rust 1.63.0</p><p>Java application is developed using <a href="https://spring.io/reactive"><strong>Reactive spring boot framework</strong></a> and it is running on top of <a href="https://netty.io/"><strong>Netty</strong></a>. Rust application is developed using <a href="https://github.com/tokio-rs/axum"><strong>Axum</strong></a> (Web application framework) and <a href="https://github.com/seanmonstar/reqwest"><strong>Reqwest</strong></a> (HTTP client), both utilizes and runs on top of <a href="https://tokio.rs/"><strong>Tokio</strong></a> runtime. Source code for demo application and gatling load test scenarios is located at <a href="https://github.com/parthmistry/single-core-performance-test"><strong>single-core-performance-test</strong></a></p><p>Before capturing any stats from load testing scenarios, applications running on single-core machine are warmed up with <strong>120 requests/sec</strong> for <strong>10 minutes</strong>. Of course <strong>Rust</strong> application doesn’t need such extensive amount of warm up (indeed doesn’t need any warm up at all), but just for sake of maintaining consistency between executing load testing scenarios on <strong>Java</strong> and <strong>Rust</strong> demo applications, I execute warm up scenarios from gatling app in all cases. Actual load testing scenarios are executed for <strong>5 minutes</strong> and statistics are captured. For different load testing scenarios, concurrent <strong>requests/sec</strong> is adjusted in such a way that CPU on single-core machine remains idle for around <strong>10% - 15%</strong> throughout the run. Here are the stats of load testing scenarios when sending concurrent requests with establishing new connection for each request -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vquFYLSGnXQqToK2M-5nJg.png" /><figcaption>Load test stats - new connection for each request</figcaption></figure><p>When load testing scenario is sending concurrent <strong>HTTP</strong> requests with new connection for each request, resulting stats looks good considering single-core machine and as we can see <strong>Rust</strong> app is able to handle <strong>~1.8</strong> times more requests per second over same hardware resources. But if we look at load testing scenario stats for sending concurrent <strong>HTTPS</strong> requests with new connection for each request, <strong>Java</strong> app is able to handle constant load of just <strong>195 requests/sec</strong>. Even if we see performance of natively generated code in <strong>Rust</strong> app, it is able to handle constant load of <strong>540 requests/sec</strong>. We can see that establishing new <strong>SSL/TLS</strong> connection involves lot of overhead due to necessary initial handshaking between client and server. In this example - load test scenario is establishing new connection for each request, however in real-world if multiple requests are coming from same browser or from some sort of HTTP client instance (programmatically) - usually subsequent requests can reuse connection from pool of already established connections which are idle. Following load testing scenario stats are based on such use case where initially set of persistent connections are established and subsequent requests are sent to the server with <strong>1 second</strong> delay from each established connection -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5tPXYyqToxYl9TvMEs1cyg.png" /><figcaption>Load test stats - reuse persistent connections</figcaption></figure><p>As we can see when sending new requests by reusing already established connections - stats are comparatively better than establishing new connection for each request. Even if we consider scenarios with <strong>HTTPS</strong> requests - with <strong>Java</strong> app it is able to handle constant load of <strong>~1100 requests/sec</strong> and with <strong>Rust</strong> app it is able to handle constant load of <strong>~1950 requests/sec</strong></p><p>In real-world - usually there is a mixed incoming traffic with some requests are establishing new connections and some requests are received on already established connections. We can expect this single-core machine can handle constant load of concurrent requests in range of the observed stats between above 2 scenarios. Remember these stats are specific to demo web application use case I have considered in this post. In my opinion - single-core machines are very much capable of serving few hundreds to thousands of requests per second and if that is not sufficient - horizontal and/or vertical scalability can always be implemented</p><blockquote>It’s <strong>“Java and Rust”</strong> not <strong>“Java vs Rust”</strong><br>Even though demo application developed with Rust outperforms application developed with Java particularly in all the scenarios discussed in this post, This post shouldn’t be seen as Java vs Rust. Performance usually depends on implementation of specific library/framework and runtime being used to run application. Different implementations usually handle different amount of complexities and offers varying degree of flexibilities. For example, Spring framework is there since couple of decades and offers lots of features and flexibilities to develop web applications. Compared to that Axum is quite new and nowhere flexible and feature rich compared to spring framework, but it provides necessary features at least to develop demo app in this post and performs a lot better than demo app running on Java. Developing an app with Rust takes time and thinking especially if developer is having past background in some language with garbage collector. Apart from that JIT dynamic compilation can generate highly efficient machine code with CPU specific instruction set, speculative optimization, dynamic inlining etc and in some cases this dynamically generated machine code could run faster than static native code generated once at compile time. I usually consider Java and Rust as just tools at my disposal to solve problems and depending on use case one might be better fit than another</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955ae3243085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuning concurrent request settings for Apache HTTP Client]]></title>
            <link>https://parthmistry241.medium.com/tuning-concurrent-request-settings-for-apache-http-client-62b9f5f0e26b?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/62b9f5f0e26b</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[apache-httpclient]]></category>
            <category><![CDATA[tuning]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Thu, 04 Aug 2022 02:35:40 GMT</pubDate>
            <atom:updated>2022-08-04T04:12:53.876Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache HTTP client library is often used in Java applications. It is easy to use and comes with both blocking and non-blocking(async) variants. Even after introduction of built-in HTTP client inside modern JDK where developers may prefer to use built-in HTTP client - Apache HTTP client still could be part of applications via use of third-party libraries that depend on it. For example when using Spring Boot RestTemplate or Elasticsearch Java API Client (or Elasticsearch Java REST Client in older versions) which internally rely on Apache HTTP client for making REST calls to the server.</p><p>In this post I am going to discuss about default settings for controlling number of concurrent requests for Apache HTTP client and how to tune them. I have prepared set of example client-server applications to check impact of tuning connection pool settings. You can refer to source code and instructions on how to run particular set of client and server applications at <a href="https://github.com/parthmistry/apache-http-client-tuning-examples">apache-http-client-tuning-examples</a>.</p><p>When an instance of Apache HTTP client with default settings is created regardless of blocking or non-blocking(async) variants, it has following connection pool settings -</p><pre>Max connections per route: 2<br>Max total connections: 20</pre><p>According to these default settings - Max connections per route controls how many concurrent requests can be sent per route (hostname + port combination). For example, if some service is running on <strong>1.2.3.4:8888</strong> then Apache HTTP client instance with default settings will just send maximum of <strong>2 concurrent requests</strong> to that service. Other concurrent requests initiated on a same route will get queued until active requests are completed. Max total connections setting controls overall maximum number of concurrent requests from given Apache HTTP client instance regardless of the route.</p><p>For testing this behavior with default settings - we can refer to <strong>demo-web</strong> application server (which is Reactive Spring Boot application) and example apps mentioned in <strong>Default HTTP Client Test</strong> section. <strong>demo-web</strong> application server has <strong>dummy API controller</strong> (/api/sample/request) which asynchronously waits for <strong>5 seconds</strong> before sending response. Also it keeps logging total number of active requests on every <strong>1 second</strong>. Blocking version of <strong>demo-client</strong> app creates single Apache HTTP client (with default settings) and spawns <strong>50 dedicated threads</strong> which attempts to send request to <strong>demo-web</strong> app server at the same time. It also logs time taken to complete each request and total time taken to complete all requests. Non-blocking version of <strong>demo-client</strong> app is similar but instead of creating <strong>50 dedicated threads</strong> for sending requests it initiates async requests from main thread and rely on <strong>callback handler</strong> to calculate total time taken to complete a request. From server logs we can observe that only <strong>2 concurrent requests</strong> are sent to the server at any given point in time.</p><p>Being able to send maximum <strong>2 concurrent requests</strong> per route sounds very limiting. Modern server applications are usually able to handle <strong>hundreds of concurrent requests</strong> without any noticeable degradation in throughput. We can tune those connection pool settings while creating an instance of Apache HTTP client -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fed1f5269afecb6d6423bf6174a577c/href">https://medium.com/media/7fed1f5269afecb6d6423bf6174a577c/href</a></iframe><p>According to these new settings - Apache HTTP client instance can send max <strong>15 concurrent requests</strong> per route. For testing this behavior with tuned settings - we can refer to <strong>demo-web</strong> application server (as mentioned previously) and example apps mentioned in <strong>Tuned HTTP Client Test</strong> section. From server logs we can observe that these tuned example apps are able to send <strong>15 concurrent requests</strong> to the server.</p><p>Many libraries are built on top of Apache HTTP client where libraries usually define higher-level library specific abstractions and rely on Apache HTTP client for lower-level HTTP based transport. Concurrent request related settings discussed in this post are applicable to such libraries as well and they usually have a way to customize default settings related to underlying Apache HTTP client. These libraries may define their own set of default settings when we don’t customize them.</p><p>Let’s take an example of Elasticsearch Java API client which is one of the popular library dependent on Apache HTTP client. It defines higher-level abstractions by which developers can easily build different kinds of requests for querying, indexing, monitoring/administrating elasticsearch server. Under the hood it depends on Apache HTTP client for sending raw HTTP requests. When an instance of Elasticsearch Java API client is created without any customization - it will consider following connection pool settings -</p><pre>Max connections per route: 10<br>Max total connections: 30</pre><p>For testing behaviors with elasticsearch client - we can refer to <strong>demo-web</strong> application server again. It has 2 elasticsearch client instances defined where one instance is using default settings and other one is using <strong>custom concurrent requests</strong> related settings defined like following -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c213e9b40abf4ff8426b630424983de/href">https://medium.com/media/3c213e9b40abf4ff8426b630424983de/href</a></iframe><p>In addition to this, <strong>demo-web</strong> application server is having <strong>2 API controllers</strong> which indexes received document in elasticsearch. First controller (/api/default/airline) is using elasticsearch client with <strong>default settings</strong> and other controller (api/tuned/airline) is using elasticsearch client with <strong>tuned settings</strong>. After document is indexed, controllers are waiting until indexed document is available for search (that is until index is refreshed which happens on every <strong>1 second</strong> as per default index setting). In real-world applications usually there may not be a requirement to wait until currently indexed document is available for search. But in my example application, just to demonstrate effect of connection pool settings against long running requests, I am choosing request pattern like this.</p><p>Example client apps mentioned in <strong>Default Index Request Test</strong> section and <strong>Tuned Index Request Test</strong> section are used to call these controllers respectively. They initiate <strong>1000 concurrent requests</strong> to the <strong>demo-web</strong> application server and logs time taken to complete each request and total time taken to complete all requests.</p><p>From server logs we can observe that all <strong>1000 requests</strong> are sent simultaneously from <strong>demo-client</strong> apps to the <strong>demo-web</strong> application server and requests to elasticsearch server are throttled according to max connections per route setting. Elasticsearch client with default settings can send <strong>10 concurrent requests</strong> to elasticsearch and takes about <strong>1 minute 43 seconds</strong> to complete <strong>1000 requests</strong> and Elasticsearch client with tuned settings can send <strong>50 concurrent requests</strong> to elasticsearch and takes about <strong>21 seconds</strong> to complete <strong>1000 requests</strong>.</p><p><strong>Summary:</strong><br>By default Apache HTTP client maintains pool of persistent connections on per route basis. Idle persistent connections from the pool can be reused to send new requests on the same route. It is helpful in a way that it reduces frequent round-trips for establishing new connections which can be time consuming. However default pool sizes might be too constraining for many modern use cases and needs to be tuned properly considering expected concurrent load and target server’s capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*xgBVqO9fjVqrBopmocsWxg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62b9f5f0e26b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuning linux network stack - with examples - Part 2]]></title>
            <link>https://parthmistry241.medium.com/tuning-linux-network-stack-with-examples-part-2-6ff94330b7b6?source=rss-e3daf5784f1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ff94330b7b6</guid>
            <category><![CDATA[network]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Parth Mistry]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 02:34:33 GMT</pubDate>
            <atom:updated>2022-06-24T02:36:03.661Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://parthmistry241.medium.com/tuning-linux-network-stack-with-examples-part-1-3a3307b7adc9"><strong>Tuning linux network stack - with examples - Part 1</strong></a>, I discussed about how tuning certain kernel level settings can affect capacity of the networking application. In this post I am going to discuss about settings which could affect throughput for the established socket connections</p><p>Similar to the previous post, I have prepared set of example client/server applications in both <strong>Java</strong> and <strong>Rust </strong>to check how networking behavior is affected after some network setting is tuned. You can refer to source code and instructions on how to run particular set of client and server applications at <a href="https://github.com/parthmistry/network-stack-tuning-examples"><strong>network-stack-tuning-examples</strong></a>. Some of the examples are using <a href="https://netty.io/"><strong>Netty</strong></a> (for <strong>Java</strong>) and <a href="https://tokio.rs/"><strong>Tokio</strong></a> (for <strong>Rust</strong>) as those examples are capable of handling thousands of active connections and creating individual threads for handling each connection is not a scalable option. All commands presented in this post are temporarily affecting network settings until host/VM is restarted</p><p>Let’s start by discussing about window scaling feature of the TCP protocol and how that feature can affect throughput in terms of data transfer rate. TCP uses windowing mechanism that regulates how much data can be sent to a receiver from a sender over network. When transferring large amount of data from sender to receiver, sender sends some amount of data (defined as per window size) and waits until acknowledgement is received from the receiver before sending next window of data. This results in efficient usage of resources on both sender and receiver side and if some packets are lost they can be re-transmitted</p><p>By original design of the TCP protocol, window size is limited to maximum of <strong>65535 bytes</strong>. Sender can’t send more than <strong>64K bytes</strong> of data until acknowledgement is received from receiver. When network bandwidth is high and latency (round-trip time) is also high, this upper limit of <strong>64K bytes</strong> window results in poor utilization of network bandwidth for the single channel. Let’s say if latency is <strong>30 ms</strong> and we can send only <strong>64K bytes</strong> at a time, we can achieve data transfer rate of <strong>17.48 Mbps</strong> even though available network bandwidth is <strong>1 Gbps</strong> or <strong>100 Gbps</strong></p><p>TCP window scaling feature is extension to original TCP protocol that allows to use much larger window size, which means more data (greater than <strong>64K bytes</strong>) can be sent by sender before receiving any acknowledgement from the receiver. In modern distributions of linux — window scaling feature is usually enabled by default and represented by <strong>net.ipv4.tcp_window_scaling</strong> setting. TCP window size depends on read/write TCP network buffer sizes of the established socket connection which can be tuned by following settings -</p><pre>net.core.rmem_default<br>net.core.rmem_max<br>net.ipv4.tcp_rmem<br>net.core.wmem_default<br>net.core.wmem_max<br>net.ipv4.tcp_wmem</pre><p>More details about these settings can be found at <a href="https://man7.org/linux/man-pages/man7/tcp.7.html">tcp: Linux Manual Pages</a>. How to tune those settings are explained a bit later in this post. When window scaling feature is disabled, setting these parameters to higher value than <strong>64K bytes</strong> will be considered for network buffer allocations but max window size over the network will be capped to <strong>64K bytes</strong>. When window scaling feature is enabled, we can take advantage of larger window size by setting these parameters to higher values than <strong>64K bytes</strong></p><p>To enable window scaling feature -</p><pre>sudo sysctl -w net.ipv4.tcp_window_scaling=1<br>sudo sysctl -p</pre><p>To disable window scaling feature -</p><pre>sudo sysctl -w net.ipv4.tcp_window_scaling=0<br>sudo sysctl -p</pre><p>Let’s check how TCP window scaling feature and network buffer size tuning affects throughput. In this example, we are going to use single threaded client and server apps. When connection is established - server app is going to repeatedly send data to the client with <strong>1 MB</strong> chunk size. While server is sending data to the client - per second data transfer bitrate is logged to the console and in the end it shows average bitrate throughout the run. For this test - we will be using client and server apps from <strong>Transfer Rate Test</strong> section</p><p>To configure various buffer sizes on client and server host we will be using following command template -</p><pre>sudo sysctl -w net.core.rmem_default=&quot;65535&quot;<br>sudo sysctl -w net.core.wmem_default=&quot;65535&quot;<br>sudo sysctl -w net.core.rmem_max=&quot;<strong>&lt;BUFFER_SIZE&gt;</strong>&quot;<br>sudo sysctl -w net.core.wmem_max=&quot;<strong>&lt;BUFFER_SIZE&gt;</strong>&quot;<br>sudo sysctl -w net.ipv4.tcp_rmem=&quot;4096 65535 <strong>&lt;BUFFER_SIZE&gt;</strong>&quot;<br>sudo sysctl -w net.ipv4.tcp_wmem=&quot;4096 65535 <strong>&lt;BUFFER_SIZE&gt;</strong>&quot;<br>sudo sysctl -p</pre><p><strong>&lt;BUFFER_SIZE&gt;</strong>in above command template should be replaced with buffer sizes (in bytes) as per the scenario</p><p>In my case, latency between client and server host is <strong>196 ms</strong>. Here is a summary statistics after running client/server apps with different combinations of buffer sizes -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGlss5lsAcHZvWf4j9i7TA.png" /></figure><p>In this example I took some arbitrary buffer sizes to demonstrate how changing them affects utilization of network bandwidth for a single channel. In real-world scenario, Bandwidth-Delay Product (<strong>BDP</strong>) can be calculated to identify optimal buffer size. Calculated <strong>BDP</strong> value specifies the optimal number of bits which can be sent by sender in order to keep the network channel full. <strong>BDP</strong> is calculated as following -</p><pre>BDP (bits) = bandwidth (bits/second) * latency (seconds)</pre><p>While calculating optimal window size it should be important to note that -<br>- Network data communication considers values in <strong>bits</strong> and <strong>1 KBit</strong> = <strong>1000 Bits</strong><br>- TCP network buffer settings consider values in <strong>bytes</strong> and <strong>1 KByte</strong> = <strong>1024 Bytes</strong></p><p>Let’s consider <strong>1 Gbps</strong> network with <strong>30 ms</strong> latency (round-trip time) then optimal <strong>BDP</strong> value is <strong>30 MBits</strong>. Which means window size should of at least <strong>3.75 MBytes</strong> and sender should be able to send that much amount of data without waiting for any acknowledgement from receiver in order to fully utilize bandwidth for a single channel. Of course calculated <strong>BDP</strong> value is just theoretical optimal number which suggests how big window size should be in order to utilize full capacity of the channel and to achieve maximum throughput. However in real-world, networks are subject to TCP protocol overheads, packet loss, network jitters etc and even receiver’s processing speed for received packets can also affect overall sender throughput</p><p>Each allocated TCP buffer consumes system memory. <strong>net.ipv4.tcp_mem</strong> setting represents bounds on how much memory can be allocated for the purpose of TCP buffers, TCP socket options and other related metadata. These bounds are measured in units of system page size. We can use following command to determine current setting values -</p><pre>$ <strong>sysctl net.ipv4.tcp_mem</strong><br>net.ipv4.tcp_mem = 190791 254389 381582</pre><p>Following command can be used to determine current system page size (in bytes) -</p><pre>$ <strong>getconf PAGESIZE</strong><br>4096</pre><p>To check current utilization of system memory for TCP buffers and other related metadata, we can use -</p><pre>$ <strong>cat /proc/net/sockstat</strong><br>sockets: used 165<br>TCP: inuse 5 orphan 0 tw 0 alloc 6 mem 1054<br>UDP: inuse 3 mem 1<br>UDPLITE: inuse 0<br>RAW: inuse 0<br>FRAG: inuse 0 memory 0</pre><p>This command outputs many of the network stack related stats and <strong>mem</strong> value for <strong>TCP</strong> represents currently utilized memory for TCP buffers and other related metadata in units of the system page size</p><p>To examine buffer size usage on server side, let’s check another example where client app will create <strong>10K</strong> active connections but won’t read any data from them. Server app will try to write as much data as possible in <strong>64 KB</strong> chunks on all established connections and fill the write buffers of each connection. Since client app is not going to read any of the received data, server app will eventually become idle as write buffers are going to be full soon and no more data can be written to the buffers from the server app until client app consumes some data. In the end server app also prints stats on how much data were written from application perspective. For this test - we will be using client and server apps from <strong>Max Send Test</strong> section. To systematically check the statistics, our example server app runs in 3 stages -</p><ol><li>Server app is up and listening for incoming connections. Once connections are accepted - writing to established socket connections won’t start until second stage starts. Server app remains in this stage for the duration specified by <strong>conn_wait</strong> (default=<strong>15s</strong>)</li><li>Server app starts writing (in parallel) to all established socket connections accepted in previous stage until write buffers are full. Server app remains in this stage for the duration specified by <strong>write_wait</strong> (default=<strong>15s</strong>)</li><li>Server app remains idle in this stage and allows us to monitor overall system memory usage for TCP and per socket network buffer usage using other tools. Server app remains in this stage for the duration specified by <strong>close_wait</strong> (default=<strong>30s</strong>)</li></ol><p>Once server app is in stage 3, we can monitor TCP memory utilizations and other statistics. To check TCP socket level memory utilizations, we can execute <strong>ss -tm</strong> command which produces output like following -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVbfYqcwxqEMxzLnalI0Hw.png" /></figure><p>Output from the previous command shows memory utilization related stats for each TCP socket connection. More details about each value specified in the output can be found at <a href="https://man7.org/linux/man-pages/man8/ss.8.html">ss: Linux Manual Pages</a>. Reading through this large output and digesting summary is hard especially when thousands of socket connections are established. Alternatively we can use example utility app mentioned in <strong>Check Server TCP Memory</strong> section which internally executes same <strong>ss -tm</strong> command but produces output in different format which is more human readable. This app shows individual socket level memory utilizations sorted by <strong>wmem_queued</strong> field and in the end shows summary statistics based on <strong>wmem_queued</strong> field. Here is a summary statistics produced by <strong>Check Server TCP Memory</strong> app when running <strong>Max Send Test</strong> client/server apps and when server is in stage 3 (with <strong>4 MB</strong> buffer size and <strong>1 GB</strong> upper bound for <strong>net.ipv4.tcp_mem</strong>)</p><pre>min: 4180 (0.004 mb)<br>max: 338736 (0.323 mb)<br>average: 105136.6496 (0.1 mb)<br>sum: 1051366496 (1002.661 mb)<br>25th percentile: 61768 (0.059 mb)<br>50th percentile: 95744 (0.091 mb)<br>75th percentile: 134256 (0.128 mb)<br>85th percentile: 168232 (0.16 mb)<br>95th percentile: 237832 (0.227 mb)<br>99th percentile: 333576 (0.318 mb)</pre><p>As we can see from the output, buffer sizes are not distributed evenly between all sockets but kernel attempts adjust allocated buffer sizes considering <strong>net.ipv4.tcp_mem</strong> bounds and currently utilized memory for the TCP buffers and other related metadata. Some sockets are getting send buffer of size <strong>150 KB</strong> or more and some of them are getting buffer sizes low as <strong>60 KB</strong> or less. Smaller allocated buffer sizes will result in smaller window</p><p>Let’s consider how changing upper bound of the <strong>net.ipv4.tcp_mem</strong> to <strong>4 GB</strong> changes distribution of buffer sizes over the same (<strong>10K</strong>) number of established socket connections</p><pre>min: 215004 (0.205 mb)<br>max: 338112 (0.322 mb)<br>average: 298133.2868 (0.284 mb)<br>sum: 2981332868 (2843.221 mb)<br>25th percentile: 236184 (0.225 mb)<br>50th percentile: 321748 (0.307 mb)<br>75th percentile: 333576 (0.318 mb)<br>85th percentile: 335256 (0.32 mb)<br>95th percentile: 335256 (0.32 mb)<br>99th percentile: 338112 (0.322 mb)</pre><p>When more memory is configured for <strong>net.ipv4.tcp_mem</strong>, buffer sizes are allocated considering that and more number of sockets are able to get larger buffer sizes. And as we have seen - if socket gets large send/receive buffer then that socket connection’s window size is adjusted accordingly for the respective read/write operation and will result in better throughput if overall network bandwidth limit is not reached</p><p>Tuning TCP buffer sizes and memory bounds are tricky parts when performing linux network stack tuning. We can start with operating system default values and make adjustments according to identified bottlenecks and limits. Here are few scenarios that could help in making decision -</p><ul><li>When considering public facing servers and having clients with varying amount of latencies and bandwidths — there are no fixed values available to calculate optimal <strong>BDP</strong> and usually medium sized buffers like <strong>2-8 MB</strong> could be appropriate depending on available system memory and expected concurrent clients. Other network monitoring tools can be used further to measure latency statistics of the connected clients and based on that buffer sizes can be adjusted over time</li><li>If packet loss is frequent in the network than buffer sizes can be kept lower to avoid frequent cycles of re-transmission for the lost packets</li><li>If we are considering server-to-server communications and bandwidth is high and so is latency, we can use large sized buffers of <strong>12-32 MB</strong> or more (depending on usecase). Doing that could result in higher memory usage for the TCP buffers and upper bounds for overall TCP memory usage should be tuned properly so that if other memory intensive applications are running in the same host then they get enough memory without crashing</li><li>When clients and servers are part of the same network or having latency lower than <strong>2-6 ms</strong> then TCP buffer sizes can be kept very low (i.e. less than <strong>200K</strong>). Depending on usecase - window scaling can also be disabled and max buffer sizes can be kept to <strong>64K</strong> without losing any network throughput. This minimizes TCP buffer memory utilization overheads and available system memory can be utilized for other purposes</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ff94330b7b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>