<?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 Ahmet Lutfu Yazici on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Lutfu Yazici on Medium]]></description>
        <link>https://medium.com/@ahmet.yazici_68066?source=rss-ce28bd5ceac5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k2MhpM3aGX4Lk96n</url>
            <title>Stories by Ahmet Lutfu Yazici on Medium</title>
            <link>https://medium.com/@ahmet.yazici_68066?source=rss-ce28bd5ceac5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:52:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmet.yazici_68066/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[Boost Golang Performance with Profile Guided Optimization]]></title>
            <link>https://medium.com/insiderengineering/boost-golang-performance-with-profile-guided-optimization-aa081759dcf7?source=rss-ce28bd5ceac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa081759dcf7</guid>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Ahmet Lutfu Yazici]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 11:33:55 GMT</pubDate>
            <atom:updated>2024-11-05T11:33:55.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s software development landscape, optimizing performance is key to reducing resource consumption, improving user experience, and lowering infrastructure costs. Go developers can enhance their applications by utilizing Profile Guided Optimization (PGO). PGO harnesses real-world profiling data to make smarter compilation decisions, resulting in faster, more efficient code. This article explores how Go developers can implement PGO to unlock the full potential of their applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OpZNc116j_LhNeEpGrV4w.jpeg" /></figure><p>With Go 1.20 and later, PGO has become accessible, allowing developers to optimize CPU usage and other performance metrics based on actual runtime behavior. In this post, we will explore what PGO is, how it works, and — most importantly — show you <strong>how to implement it</strong> in your own Go applications. From building an instrumented version of your app to collecting runtime profiles and recompiling with PGO, we’ll walk through the steps to unlock your app’s full potential.</p><h3>How PGO Internally Works</h3><p>Profile Guided Optimization (PGO) does more than just optimize the frequently executed parts of your Go application. Internally, the Go compiler uses various sophisticated techniques to improve performance based on the data collected from the runtime profile. These optimizations include function inlining, devirtualization, escape analysis, and branch prediction, among others. Let’s explore how these internal mechanisms work and how they boost application performance.</p><h4>1. Inlining: Reducing Function Call Overhead</h4><p>Inlining is a compiler optimization that replaces a function call with the actual code of the function itself, eliminating the overhead associated with making the function call. This optimization is especially beneficial for improving the performance of <strong>hot functions</strong> — those that are frequently called and have a significant impact on overall performance.</p><p>While inlining is useful for small functions, it is especially valuable for hot functions that are called repeatedly during execution. These functions contribute the most to performance bottlenecks, so eliminating the overhead of function calls in these sections of code can lead to noticeable performance improvements.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iZWIrzpZpIsgu01J" /></figure><p>Without inlining, the program would make a function call to Add. With inlining, the Go compiler replaces the function call with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YZMp3aQHANfFUoTR" /></figure><p>This eliminates the overhead of calling the function, but without PGO, this decision is based solely on the size and simplicity of the Add function, not its actual runtime importance.</p><h4>2. Escape Analysis: Optimizing Memory Usage</h4><p>In Go, <strong>escape analysis</strong> is used to determine whether a variable can be safely allocated on the stack (faster) or must be allocated on the heap (slower, but required for data that needs to persist beyond a function’s execution). Allocating variables on the stack is much more efficient, but if a variable “escapes” its function (i.e., it’s referenced outside of the function where it was created), it must be allocated on the heap to avoid issues with memory access.</p><p>With PGO, the Go compiler uses profiling data to gain deeper insights into memory usage patterns. This enables more precise decisions about where to allocate memory, reducing the frequency of heap allocations and improving performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SdCLPN7_vdzL-3lm" /></figure><p>In this example, the NewFoo function creates a new Foo struct and returns a pointer to it. Because the pointer escapes the NewFoo function and is used by ComputeFoo, the Go compiler must allocate the Foo struct on the heap to ensure it remains accessible after NewFoo exits.</p><p>However, with PGO, if the profiling data shows that ComputeFoo is called frequently and the allocated memory is short-lived (used only within the ComputeFoo function), the Go compiler can optimize this by allocating Foo on the stack instead of the heap. This reduces the need for garbage collection and improves memory efficiency.</p><h4>3. Devirtualization: Eliminating Indirection</h4><p>In some programs, functions are called indirectly through interfaces. This requires the compiler to figure out which concrete function to call at runtime, adding overhead.</p><p>With PGO, the compiler uses profiling data to understand which specific types are most often used in interface calls and can eliminate the need for runtime dispatch by <strong>devirtualizing</strong> these calls. This means the compiler can directly call the appropriate function rather than relying on dynamic dispatch at runtime.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TjNeoTm7ULXSpKdF" /></figure><p>Without devirtualization, this call goes through an indirection layer to figure out which Work method to execute. With PGO, if the profiling data shows that Engineer is the most common type assigned to Worker, the Go compiler can devirtualize the call, directly calling Engineer.Work().</p><h4>4. Branch Prediction: Improving Conditional Logic</h4><p>Branch prediction is an optimization technique that predicts which way a branch (an if/else condition or a switch statement) will go based on previous executions. Modern CPUs have hardware branch predictors, but incorrect predictions still introduce performance penalties.</p><p>PGO enhances branch prediction by using actual runtime data to guide the compiler in optimizing the most likely branches in your code. If, during profiling, a certain branch is taken 90% of the time, the compiler can optimize that path, reducing CPU cycles spent on incorrect predictions.</p><p><strong>Example</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Swh6lJVGs28GWtov" /></figure><p>Without PGO, the compiler has no insight into how often the flag is true or false. With PGO, if the profile data shows that flag is usually true, the Go compiler will prioritize the true branch for faster execution.</p><h3>How to Use PGO</h3><p>Profile Guided Optimization (PGO) in Golang is a three-step process that enables the compiler to optimize your application based on actual runtime behavior. By leveraging profiling data collected during real-world execution, PGO allows the Go compiler to make smarter decisions about which parts of the code should be optimized. Below, we’ll walk through each phase of how PGO works, including a practical example using net/http/pprof for data collection.</p><h4>1. Instrumentation: Preparing the Program for Profiling</h4><p>The first step in the PGO process is to instrument your Go application to collect profiling data. This is done by adding profiling hooks to your application, allowing it to record performance metrics during execution. For web-based applications, you can easily achieve this using the built-in net/http/pprof package.</p><p>Here’s how to set up net/http/pprof in your Go application:</p><pre>import (<br>    &quot;net/http&quot;<br>    _ &quot;net/http/pprof&quot; // Automatically registers profiling handlers<br>)</pre><pre>func main() {<br>    // Your normal HTTP handlers<br>    http.HandleFunc(&quot;/&quot;, handler)</pre><pre>// Start the HTTP server, which now includes pprof endpoints<br>    http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><h4>2. Data Collection: Gathering Real-World Performance Data</h4><p>After instrumenting your Go application, the next step is to run it under realistic workloads to gather performance data. This data is critical for informing the Go compiler about the most frequently executed code paths (hot paths) in your application, enabling it to optimize those sections during recompilation.</p><p>You can simulate a real-world workload by generating traffic using load-testing tools like <strong>K6</strong> or <strong>Locust</strong>:</p><p><strong>Using K6</strong>:<br>K6 is a popular, scriptable load-testing tool that allows you to easily define scenarios to simulate traffic:</p><pre>import http from &#39;k6/http&#39;;<br>import { sleep } from &#39;k6&#39;;</pre><pre>export default function () {<br>    http.get(&#39;http://localhost:8080/&#39;);<br>    sleep(1); // Simulates a delay between requests<br>}</pre><p>To execute the load test:</p><pre>k6 run load_test.js</pre><p><strong>Using Locust</strong>:</p><p>Locust is another powerful load-testing framework, written in Python, to simulate multiple users interacting with your application:</p><pre>from locust import HttpUser, task, between</pre><pre>class MyUser(HttpUser):<br>    wait_time = between(1, 2)</pre><pre>@task<br>    def index(self):<br>        self.client.get(&quot;/&quot;)</pre><p>Run the Locust test with:</p><pre>locust -f locust_test.py</pre><p>Once you’ve set up a load test using <strong>K6</strong> or <strong>Locust</strong> and your application is running under typical conditions, you can begin collecting profiling data.</p><h4>Collecting CPU Profile Data</h4><p>To gather CPU profiling data, you can use the net/http/pprof package, which exposes profiling endpoints. While your load test is running, execute the following command to collect a 30-second CPU profile:</p><pre>curl http://localhost:8080/debug/pprof/profile?seconds=30 -o cpu.prof</pre><p>This command saves the CPU profiling data into a cpu.prof file. It tracks which functions consume the most CPU time, helping the compiler focus its optimizations on the most resource-intensive sections of your application.</p><p>By combining these profiling techniques with real-world workloads simulated by <strong>K6</strong> or <strong>Locust</strong>, you ensure that the collected data reflects actual production conditions. This step lays the groundwork for the final optimization phase, where the Go compiler will use the profiling data to build a more efficient version of your application.</p><h4>3. Optimization: Recompiling the Application with Profiling Data</h4><p>Now that you have collected the profiling data, you can recompile your Go application using this profile to guide the optimizations. The Go compiler will use this information to optimize hot paths, inline functions, and improve performance based on actual usage patterns.</p><p>To recompile your application using the collected profile, run:</p><pre>go build -pgo=cpu.prof -o bin/optimized</pre><p>This command informs the Go compiler to use the cpu.prof file for Profile Guided Optimization, resulting in an optimized binary tailored to the real-world performance characteristics of your application.</p><p>By following these steps, your program can become <strong>faster by anywhere between 2% and 15%</strong>, depending on which optimizations are applied and how critical the optimized code paths are to overall performance. Applications that have clear hot paths or frequent function calls tend to benefit the most from inlining and branch prediction optimizations.</p><h3>4. Real-World Scenario: Applying PGO to a Go Web Application</h3><p>To illustrate how Profile Guided Optimization (PGO) can be used to optimize a real-world Go application, let’s walk through a scenario using the provided source code. This application is a simple user management API that uses PostgreSQL as the database and Redis as a cache. We’ll show how you can apply PGO to this application to enhance its performance using load testing with the <strong>K6</strong> framework.</p><h4>The Application Setup</h4><p>The provided Go application consists of basic CRUD operations (Create, Read, Update, Delete) for a User entity, with validation via the go-playground/validator package. The API integrates with a PostgreSQL database using GORM and caches user data in Redis. Here’s a breakdown of the key components:</p><ul><li><strong>Database (PostgreSQL)</strong>: Stores user data.</li><li><strong>Redis Cache</strong>: Caches user data for quicker retrieval.</li><li><strong>Validation</strong>: Validates incoming user data using the validator package.</li><li><strong>Profiling</strong>: The app uses the net/http/pprof package to enable profiling, which will allow us to collect runtime data for PGO.</li></ul><p><strong>main.go</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca1788c5921e97d5aec780fb04194561/href">https://medium.com/media/ca1788c5921e97d5aec780fb04194561/href</a></iframe><h4>The Load Test with K6</h4><p>We simulate load on the application using the <strong>K6</strong> framework with a provided test script. The test performs the following actions:</p><ol><li>Creates a user with a unique email.</li><li>Retrieves the created user.</li><li>Updates the user’s information.</li><li>Deletes the user.</li></ol><p>The load test simulates multiple users concurrently accessing the API. Here’s the K6 script (tests/test.js):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dc4ddcd903853b1595864a7109f7cb1/href">https://medium.com/media/1dc4ddcd903853b1595864a7109f7cb1/href</a></iframe><h4>Step-by-Step Guide to Applying PGO</h4><ol><li><strong>Instrumentation: Enabling Profiling</strong><br>The application already imports the net/http/pprof package, which exposes profiling endpoints. This allows us to collect CPU profile data while the application is under load. Ensure that the profiling endpoints are accessible via /debug/pprof/.</li></ol><pre>import _ &quot;net/http/pprof&quot;  // Already included in main.go</pre><p>2. <strong>Data Collection: Running the Load Test with K6</strong><br>Run the application and the K6 load test to simulate a real-world workload. While the load test is running, collect the CPU profile data by accessing the /debug/pprof/profile endpoint.</p><p><strong>Run the Go application</strong>:</p><pre>go run main.go</pre><p><strong>Run the K6 load test</strong>:</p><pre>k6 run tests/test.js</pre><p><strong>Collect the CPU profile data</strong> during the load test:</p><pre>curl http://localhost:8080/debug/pprof/profile?seconds=30 -o cpu.prof</pre><p>This command collects a 30-second CPU profile, which will guide the compiler in optimizing the performance-critical code paths.</p><p>3. <strong>Optimization: Rebuilding the Application with PGO</strong></p><p>Once the profiling data has been collected, recompile the application using the CPU profile (cpu.prof) for PGO:</p><pre>go build -pgo=cpu.prof -o bin/optimized</pre><p>The Go compiler will use the profiling data to optimize frequently executed code paths, such as inlining hot functions, optimizing branch predictions, and reducing unnecessary heap allocations.</p><p>4. <strong>Compare Profiling Data Before and After Optimization</strong><br>After optimizing your Go application using PGO, it’s helpful to compare the profiling data before and after optimization to measure the improvements.</p><ul><li><strong>Collect profiling data after optimization</strong> using the recompiled application:</li></ul><pre>curl http://localhost:8080/debug/pprof/profile?seconds=30 -o optimized_cpu.prof</pre><ul><li><strong>Use </strong><strong>go tool pprof to compare the two profiles</strong> (cpu.prof and optimized_cpu.prof) and see how the optimization has affected your application:</li></ul><pre>go tool pprof -diff_base cpu.prof optimized_cpu.prof</pre><p>This command generates a comparison between the original and optimized profiles, showing which parts of the code have been improved and how the CPU usage has changed after applying PGO. This is a valuable step for validating the effectiveness of your optimizations.</p><h3>Further Reading on Profile Guided Optimization in Go</h3><p>For more in-depth insights and examples of how Profile Guided Optimization (PGO) can enhance Go performance, check out these valuable resources:</p><ul><li><a href="https://go.dev/blog/pgo">Official Go PGO Blog</a> — A detailed overview from the Go team on how PGO works and how to implement it.</li><li><a href="https://blog.cloudflare.com/reclaiming-cpu-for-free-with-pgo/">Cloudflare’s PGO Experience</a> — Learn how Cloudflare leveraged PGO to reclaim CPU cycles and improve efficiency.</li><li><a href="https://landontclipp.github.io/blog/2023/08/25/profile-guided-optimizations-in-go/">Profile Guided Optimizations in Go</a> — A technical deep dive into using PGO in Go by Landon Clipp.</li></ul><p>If you found this article insightful, don’t miss out on more great content! Visit the <a href="https://medium.com/insiderengineering">Insider Engineering Medium Page</a> to stay updated on the latest trends and innovations in software development. Here are some other blogs you might enjoy exploring:</p><ul><li><a href="https://medium.com/insiderengineering/concurrent-http-requests-in-golang-best-practices-and-techniques-f667e5a19dea">Concurrent HTTP Requests in Golang: Best Practices and Techniques</a></li><li><a href="https://medium.com/insiderengineering/how-we-saved-85-of-costs-by-moving-aws-lambda-from-node-js-to-golang-b068498b6e97">How we saved 85% of costs by moving AWS Lambda from Node.js to Golang</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa081759dcf7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insiderengineering/boost-golang-performance-with-profile-guided-optimization-aa081759dcf7">Boost Golang Performance with Profile Guided Optimization</a> was originally published in <a href="https://medium.com/insiderengineering">Insider One Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>