<?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 Pranoy Kundu on Medium]]></title>
        <description><![CDATA[Stories by Pranoy Kundu on Medium]]></description>
        <link>https://medium.com/@pranoy1998k?source=rss-3714d8983989------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-5wrBlsqI4TdoqFeXFPpKA.jpeg</url>
            <title>Stories by Pranoy Kundu on Medium</title>
            <link>https://medium.com/@pranoy1998k?source=rss-3714d8983989------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:43:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pranoy1998k/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[Dealing with lost wakeup problem, understanding sync.Cond in Go]]></title>
            <link>https://medium.com/@pranoy1998k/dealing-with-lost-wakeup-problem-understanding-sync-cond-in-go-65f00213979a?source=rss-3714d8983989------2</link>
            <guid isPermaLink="false">https://medium.com/p/65f00213979a</guid>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[lost-wakeup]]></category>
            <category><![CDATA[synchronization]]></category>
            <dc:creator><![CDATA[Pranoy Kundu]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 16:21:12 GMT</pubDate>
            <atom:updated>2025-11-16T05:54:13.695Z</atom:updated>
            <content:encoded><![CDATA[<p>I was recently working on setting up a pool manager in my service. I implemented a simple approach using sync.Mutex and chan struct{}. But I ended up with a race condition and a lost wakeup problem.</p><blockquote>A <strong>lost wakeup</strong> problem in Go, refers to a scenario where a goroutine that is meant to be woken up by a signal or notification misses that signal because it was not yet in a waiting state when the signal was sent.</blockquote><p>Let us look into what caused the problem and how I solved it using sync.Cond.</p><p>Below was my initial structure</p><pre>type pool struct {<br>  connections conn<br>  lk sync.Mutex<br>  available chan struct{}<br>}</pre><p>The idea was to create two functions from it - GetAvailableConnection() and ReleaseConnection(). These two methods will be accessed concurrently by multiple go routines.</p><pre>func (p *pool) GetAvailableConnection() conn {<br>   for {<br>    p.lk.Lock()<br>    for _, c := range p.conn {<br>      // Search for available connection and return if exists<br>      p.lk.Unlock()<br>      return conn<br>     }<br>    p.lk.Unlock()<br>    // All connections busy, wait for one to become available<br>    &lt;-p.available<br>  }<br> }<br><br>func (p *pool) ReleaseConnection(conn *conn) {<br>  p.lk.Lock()<br>  // release connection<br>  p.lk.Unlock()<br>  // Signal that a connection is now available<br>  select {<br>  case p.available &lt;- struct{}{}:<br>  default:<br>  }<br> }</pre><p>This approach looks simple and fine at a glance but there is a critical bug in this which can induce a lost wakeup problem.</p><p>The problem in detail -</p><ol><li><strong>Goroutine A</strong> (a request) calls GetAvailableConnections</li><li>Goroutine A locks the mutex, sees all connections are busy, and <strong>unlocks the mutex</strong>.</li><li><strong>AT THIS EXACT MOMENT</strong>, before Goroutine A can start waiting on the channel, <strong>Goroutine B</strong> (another request) finishes its work and calls ReleaseConnection.</li><li>Goroutine B locks the mutex, marks a connection as available, and <strong>sends on the </strong><strong>p.available channel</strong>.</li><li>Goroutine B unlocks the mutex and exits.</li><li><strong>Now</strong>, Goroutine A finally runs Step 4 and starts waiting on &lt;-p.available.</li></ol><p><strong>The result:</strong> Goroutine A is now waiting forever for a signal that has already been sent and missed<strong>.</strong> A connection is free, but Goroutine A is stuck. This is a classic “<strong>lost wakeup</strong>” problem.</p><p>To fix the problem we can use the sync.Cond type in Go. Let’s understand more about it.</p><h3>What is the sync package?</h3><p>To understand sync.Cond let us first recap what the <strong>sync package </strong>is. Sync package provides all the basic synchronization primitives such as mutual exclusive locks, waitGroups, and various other types. Most of the types provided are intended to be used by low level library routines.</p><h3>What is sync.Cond?</h3><p>sync.Cond implements a condition variable, a rendezvous point for all waiting GoRoutines or for announcing an occurrence of an event. It uses a locker L (sync.Mutex or sync.RWMutex) which we need to hold when waiting for an announcement or a signal.</p><p>It has 4 functions -</p><ol><li><strong>NewCond</strong> -</li></ol><p>To initialize a new sync.Cond variable -</p><pre>c := sync.NewCond(&amp;sync.Mutex{})</pre><p>2.<strong> c.Wait</strong> -</p><p>It atomically unlocks the lock (c.L) we hold and puts the goroutine to sleep. Wait cannot return without being woken up. To wake up Wait we need to use cond.Broadcast or cond.Signal. Since c.L is not locked when the caller is waiting in the function, the caller typically cannot assume that the condition is true when Wait returns. The Wait needs to wait in a loop.</p><p>3. <strong>c.Signal</strong> -</p><p>A Signal method wakes up one goroutine waiting on c, if there is any.</p><p>4. <strong>c.Broadcast</strong> -</p><p>Broadcast wakes up all goroutines waiting on c.</p><p>Now by using the above 4 functions we modify our initial code like below -</p><pre>type pool struct {<br>  connections conn<br>  cond *sync.Cond<br>}<br><br>func (p *pool) GetAvailableConnection() *conn {<br>  p.cond.L.Lock()<br>  for {<br>    for _, conn := range p.conn {<br>      // Search for available connection and return if exists<br>      p.cond.L.Unlock()<br>      return conn<br>    }<br>    // No connection available. Wait for one.<br>    p.cond.Wait()<br>  }<br>}<br><br>func (p *pool) ReleaseConnection(conn *conn) {<br>  p.cond.L.Lock()<br>  // release connection<br>  p.cond.L.Unlock()<br>  // Wake up ONE goroutine that might be waiting in p.cond.Wait()<br>  p.cond.Signal()<br>}</pre><p>Now let’s see how we solved our problem with this approach -</p><ol><li><strong>Goroutine A</strong> locks, sees all connections are busy.</li><li>Goroutine A calls p.cond.Wait. This <strong>atomically unlocks and sleeps</strong>.</li><li><strong>Goroutine B</strong> (the releaser) can now acquire the lock. It sets available, unlocks, and calls p.cond.Signal().</li><li>Because Goroutine A was <em>guaranteed</em> to be on the wait list <em>before</em> the lock was released, it <strong>safely receives the signal</strong>.</li></ol><p>Here we use sync.Cond to acquire a single lock while checking availability and signalling availability. This solves our problem of “<strong>lost-wakeup</strong>”.</p><p>Now I can also create a method like below to release all the waiting goroutines at once</p><pre>func (p *pool) ReleaseAllConnections() {<br>  p.cond.L.Lock()<br>  defer p.cond.L.Unlock()<br>  // release all connections<br>  // Send signal to all the waiting goroutines<br>  p.cond.Broadcast()<br>}</pre><h3><strong>Conclusion</strong></h3><p>In conclusion, the “lost wakeup” problem is a subtle yet critical bug that can arise in concurrent Go programs. It highlights a classic race condition where a signal is sent before the intended receiver is actually waiting, causing the waiting goroutine to sleep indefinitely.</p><p>Go’s sync.Cond provides a robust solution for this exact scenario. Its power lies in the Wait() method, which atomically unlocks the associated mutex and puts the goroutine to sleep in a single, indivisible step.</p><p>This atomic operation is the key to preventing the lost wakeup. It guarantees that the waiting goroutine is verifiably on the wait list before the signaling goroutine can ever acquire the lock to send its notification.</p><h3><strong>References -</strong></h3><ol><li><a href="https://pkg.go.dev/sync">https://pkg.go.dev/sync</a></li><li><a href="https://www.youtube.com/watch?v=5zXAHh5tJqQ">https://www.youtube.com/watch?v=5zXAHh5tJqQ</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65f00213979a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Escape Analysis in Go]]></title>
            <link>https://medium.com/@pranoy1998k/understanding-escape-analysis-in-go-b2db76be58f0?source=rss-3714d8983989------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2db76be58f0</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[go-performance]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[escape-analysis]]></category>
            <category><![CDATA[heap-vs-stack]]></category>
            <dc:creator><![CDATA[Pranoy Kundu]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 07:44:01 GMT</pubDate>
            <atom:updated>2024-03-16T07:44:01.504Z</atom:updated>
            <content:encoded><![CDATA[<p>Go uses escape analysis to determine the dynamic scope of Go values. Typically, go tries to store all the Go values in the <em>function stack frame</em>. The go compiler can predetermine which memory needs to be freed and emits machine instructions to clean it up. This way it becomes easy to clean up memory without the intervention of the Go Garbage Collector. This way of allocating memory is typically called <em>stack allocation</em>.</p><p>But when the compiler cannot determine the lifetime of a Go value it <em>escapes to the heap</em>. A value may also escape to the heap when the compiler does not know the size of the variable, or it’s too large to fit into the stack, or if the compiler cannot determine whether the variable is used after the function ends or the function stack frame is not used anymore.</p><p>Even said so can we truly and completely know whether the value is stored in the heap or stack? The answer is NO. Only the compiler would know where exactly the value is stored all the time. As mentioned in this <a href="https://tip.golang.org/doc/gc-guide">doc</a><em> “The Go language takes responsibility for arranging the storage of Go values; in most cases, a Go developer need not care about where these values are stored, or why, if at all.”</em></p><p>There might still be scenarios where we might want to know the allocation to improve performance. As we know, <em>physical memory is finite</em> and overuse of it might result in unnecessary performance issues.</p><p>Let’s now see how we can determine when and why a variable escapes to the heap. We will use the <strong>go build</strong> command to determine it. Run <strong>go help build</strong> to get various options for go build. We will use <strong>go build -gcflags=”-m” </strong>command to ask the compiler where the variables are being put. Let’s now go through some examples to determine it:</p><ol><li>In this example, we call a square function from our main function</li></ol><pre>package main<br><br><br>func main() {<br>   x := 2<br>   square(x)<br>}<br><br><br>func square(x int) int {<br>   return x*x<br>}</pre><p>When we run the above code with <strong>go build -gcflags=”-m”</strong> we get the below result</p><pre># github.com/pranoyk/escape-analysis<br>./main.go:8:6: can inline square<br>./main.go:3:6: can inline main<br>./main.go:5:8: inlining call to square</pre><p>Right now everything is in stack frame.</p><p>2. Let’s now modify our code to return a pointer from the square function</p><pre>package main<br><br><br>func main() {<br>   x := 2<br>   square(x)<br>}<br><br><br>func square(x int) *int {<br>   y := x*x<br>   return &amp;y<br>}</pre><p>When we build this code we get</p><pre># github.com/pranoyk/escape-analysis<br>./main.go:8:6: can inline square<br>./main.go:3:6: can inline main<br>./main.go:5:8: inlining call to square<br>./main.go:9:2: moved to heap: y</pre><p>Here the value `y` escaped to heap. Now notice why this happened. The value of `y` has to prevail once the square function life cycle has finished and hence it escapes to the heap.</p><p>3. Let’s modify the above function. Let’s make our square function accept a pointer and not return a value.</p><pre>package main<br><br><br>func main() {<br>   x := 4<br>   square(&amp;x)<br>}<br><br><br>func square(x *int)  {<br>   *x = *x**x<br>}</pre><p>When we build the above code we get</p><pre># github.com/pranoyk/escape-analysis<br>./main.go:8:6: can inline square<br>./main.go:3:6: can inline main<br>./main.go:5:8: inlining call to square<br>./main.go:8:13: x does not escape</pre><p>Notice in the above function even though we are passing the pointer to the square the compiler mentions that the variable `x` does not escape. This is because the variable `x` is created in the main function stack frame which lives longer than the square function stack frame.</p><p>4. Let’s make one more modification to the above code. Let’s make our square function both accept and return a pointer.</p><pre>package main<br><br><br>func main() {<br>   x := 4<br>   square(&amp;x)<br>}<br><br><br>func square(x *int) *int {<br>   y := *x**x<br>   return &amp;y<br>}</pre><p>The allocation of above code is</p><pre># github.com/pranoyk/escape-analysis<br>./main.go:8:6: can inline square<br>./main.go:3:6: can inline main<br>./main.go:5:8: inlining call to square<br>./main.go:8:13: x does not escape<br>./main.go:9:2: moved to heap: y</pre><p>Now notice carefully that the result of this code is a combination of examples 2 &amp; 3. If we look even further closely we can say that sharing memory down from the <em>main to another function typically stays on the stack</em> and sharing memory up from a <em>function to the main typically escapes to the heap</em>. We can never be completely sure about it always because only the compiler would truly know where the value is stored. But this still gives some hint when an escape to the heap may occur.</p><h3>Conclusion</h3><ul><li>Escape analysis in Go is a way in which the compiler determines whether the value is to be stored in the stack frame or the heap.</li><li>Anything that cannot be stored in the function stack frame escape to the heap.</li><li>We can check the memory allocation of our code using `go build -gcflags=”-m”`.</li><li>Although, go manages the memory allocation quite efficiently and almost always a developer might not be concerned with it. It’s still good to know in case you want to improve on the performance.</li></ul><h3>References</h3><ul><li><a href="https://www.youtube.com/watch?v=ZMZpH4yT7M0">https://www.youtube.com/watch?v=ZMZpH4yT7M0</a></li><li><a href="https://tip.golang.org/doc/gc-guide">https://tip.golang.org/doc/gc-guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2db76be58f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B Testing with Linkerd and Flagger using Dynamic Routing]]></title>
            <link>https://medium.com/infracloud-technologies/a-b-testing-with-linkerd-and-flagger-using-dynamic-routing-0f3eae052a0d?source=rss-3714d8983989------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f3eae052a0d</guid>
            <category><![CDATA[linkerd]]></category>
            <category><![CDATA[flagger]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <dc:creator><![CDATA[Pranoy Kundu]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 04:51:25 GMT</pubDate>
            <atom:updated>2024-01-29T04:51:25.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7tPR1MQTC8YgW_v7NDOyQ.png" /></figure><p>Managing the flow of requests between different services is a crucial aspect of communication among services. Request routing enables us to direct incoming traffic to specific services based on various criteria, such as headers, query parameters, or other aspects of the request. Request routing is essential, but it can become challenging to manage with existing tools.</p><p>Suppose you have a microservices-based application with multiple service versions running simultaneously. You wish to gradually roll out a new version of the application to a subset of users for A/B testing. However, the existing load balancers or ingress controllers lack the granular control for such a scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c9C8lkqsjMuCdRI8.png" /><figcaption>(A/B testing with ingress controller)</figcaption></figure><p>When using a traditional ingress controller in this scenario, you deploy both versions of your checkout service (A and B) behind the ingress controller. The absence of fine-grained traffic splitting capabilities in traditional ingress controllers means you have to configure manual techniques like DNS-based routing or custom configurations to divide the traffic between the two versions. Additionally, setting up separate monitoring and alerting systems becomes necessary to collect metrics and detect issues with both service versions, leading to complexity and time-consuming efforts.</p><p>This is where service mesh like <a href="https://linkerd.io/2.13/overview/">Linkerd</a> comes to the rescue. Service mesh provides a dedicated infrastructure layer that handles communication between microservices. They offer advanced features like dynamic request routing, service discovery, traffic control, and observability. By leveraging Linkerd’s dynamic request routing feature, we can easily route specific requests to different versions of services based on custom criteria, making A/B testing and gradual rollouts a breeze. If you want to know more about what are service meshes, and the benefits they bring, read this <a href="https://www.infracloud.io/blogs/service-mesh-101/">blog post on service mesh 101</a>.</p><p>Linkerd’s dynamic request routing feature has been introduced in Linkerd 2.13. It leverages the <a href="https://gateway-api.sigs.k8s.io/">Kubernetes Gateway API</a> feature, which reduces the amount of new configuration machinery introduced onto the clusters while still providing a rich and expressive feature set. In this blog post, we will look at Linkerd’s dynamic request routing feature and use it for A/B testing using Flagger.</p><p>First, let’s understand the dynamic request routing.</p><h3>What is dynamic request routing?</h3><p><a href="https://linkerd.io/2.13/tasks/configuring-dynamic-request-routing/">Dynamic request routing</a> means that the route’s location is decided at the runtime by some predefined protocols or algorithms. The routing can be at different times or different locations.</p><h3>What is the role of dynamic request routing?</h3><p>Dynamic request routing can be used to deliver a variety of exciting features onto your platform:</p><ol><li>Sticky sessions</li><li>A/B testing</li><li>Dynamic staging environment</li><li>User-based canary rollouts</li></ol><p>Dynamic request routing also helps with some additional functions like:</p><ul><li>Increasing flexibility to route the traffic.</li><li>Improving security by restricting unauthorized access to application resources.</li><li>Reducing complexity due to the reduction of your application’s routing logic. It also results in ease in maintaining and troubleshooting application routes.</li></ul><p>As we covered dynamic request routing, let’s now understand A/B testing quickly.</p><h3>What is A/B testing?</h3><p>A/B testing is a methodology to test two versions of a webapp or an application. It’s an experiment where two or more variations of a variable like web page, route, etc., are shown to users at random or to a predefined set of users. Developers can later collect different metrics and do a statistical analysis to determine which process suits the users better. With statistical analysis, developers and product managers can move from <em>‘we think’</em> to <em>‘we know’</em> on what works best for the user and where the team needs to focus more on improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*j6yBJzhL70_5iRUw.png" /></figure><h3>Why A/B testing?</h3><p>There are many reasons organizations do A/B testing. Some of the reasons are:</p><ul><li>A/B testing helps in making conscious changes to the product based on the analytical feedback.</li><li>We can continuously run A/B testing to improve the product based on the experience continually.</li><li>With A/B testing, we can move entirely towards making our decisions based on reliable data rather than guesswork.</li><li>A/B testing also helps in making incremental changes to your webpage based on feedback in the form of statistical analysis.</li><li>A/B testing helps you increase user engagement by identifying and optimizing the elements that resonate best with your audience.</li></ul><h3>How to perform A/B testing?</h3><p>To design a practical A/B test, consider the following key elements:</p><ol><li><strong>Define A and B versions</strong>: Based on the hypothesis created, you can deploy the baseline version (A) and the new version (B) of your application also called as canary version. These versions can include different features, UI changes, or any modifications you want to test. Remember that you have to keep everything else the same in both app versions except the changes you wish to test.</li><li><strong>Configure routing</strong>: Define specific HTTP headers (e.g., x-backend) to route traffic to the canary environment. Ensure that only a fraction of the traffic is routed using these headers. We use this approach to target specific users or segments for A/B testing.</li><li><strong>Monitor metrics and analyze results</strong>: Monitor metrics such as request success rate, latency, error rates, etc. Compare metrics between versions A and B and detect anomalies or deviations.</li><li><strong>Compare and decide</strong>: Analyze the result for some time and make an informed decision on which version of the application performs better.</li><li><strong>Rollback and iteration</strong>: If metrics indicate a negative impact, you can easily roll back to baseline version A.</li></ol><h3>Flagger and Linkerd</h3><p><a href="https://flagger.app/">Flagger</a> and <a href="https://linkerd.io/">Linkerd</a> work together to enable controlled rollouts and monitoring within a Linkerd-powered service mesh. Flagger automates creating the required Linkerd resources and orchestrates canary deployments. It creates new Kubernetes resources for the new release, configures traffic splitting rules, and monitors metrics and health checks. Flagger incrementally shifts user traffic to the new version based on predefined criteria and monitors the performance and health of the canary deployment using Linkerd’s observability features. If the canary version meets the defined criteria, Flagger automatically promotes it to full production. Otherwise, it can roll back to the stable version. This integration streamlines the process of canary deployments, making it easier to release new versions while ensuring a smooth transition and minimizing disruptions for end users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TGJEUkpJ89LB-CW0.png" /><figcaption><a href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRLBHpExSTPVN7M6dZgLgfvy4wGd4zuI2AnQCKtICVohixdgQMzcChVd21qzoE5A509jqU&amp;usqp=CAU">(A/B testing using Linkerd and Flagger)</a></figcaption></figure><p>By leveraging Flagger with Linkerd, you can conduct effective A/B testing, make data-driven decisions, and continuously improve your application.</p><h3>A/B testing using Linkerd and Flagger</h3><p>In this section, we’ll set up Linkerd and Flagger to perform A/B testing. We’ll be using the bookinfo application, which is a microservice-based <a href="https://github.com/infracloudio/ab-testing-linkerd-flagger">application</a>. In the following steps we will clone this application and set it up. The application has different services, and we’ll see how the traffic shifts.</p><h3>Prerequisites</h3><ul><li>Kubernetes kind/minikube cluster, and it must be enabled with the ingress controller. In this post, we’re using Kind.</li><li><a href="https://linkerd.io/2.13/tasks/install/">Linkerd must be installed</a> and configured with the cluster.</li><li><a href="https://linkerd.io/2.13/tasks/linkerd-smi/#cli">Linkerd-SMI</a> and <a href="https://linkerd.io/2.13/tasks/troubleshooting/#l5d-viz-ns-exists">Linkerd-viz</a> extensions must be installed.</li><li><a href="https://docs.flagger.app/install/flagger-install-on-kubernetes">Flagger must be installed</a>.</li></ul><h3>Header based testing</h3><p>The header-based testing approach utilizes headers to direct traffic to different versions of the application. This strategy employs HTTP headers for routing requests, providing an advanced method for controlling the distribution of traffic. By leveraging tools like Flagger and Linkerd, this approach enables precise header-driven routing.</p><p>This feature is valuable in A/B testing scenarios where you want to target a particular segment of users using HTTP headers or cookies. It is especially beneficial for front-end applications that rely on session affinity to ensure a consistent user experience. This can be used when we have a set of predefined users that we want to route to the latest version.</p><h4>Set up the demo</h4><p>This demo consists of the components book-svc deployment, book-svc service, and load-generator. <br>The book-svc deployment represents a microservice that exposes book-info APIs.<br>A load generator is used to simulate real-world traffic and test the canary deployment. The load generator generates live traffic for the application, allowing Flagger to monitor and analyze the behavior of the deployed versions effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nDg23h18s8-Dnys3.png" /></figure><p>Clone <a href="https://github.com/infracloudio/ab-testing-linkerd-flagger">application</a>:</p><pre>git clone https://github.com/infracloudio/ab-testing-linkerd-flagger.git</pre><p>To add these components to your cluster and configure with Linkerd, run the following:</p><pre>kubectl create ns test --dry-run=client -o yaml \<br>  | linkerd inject - \<br>  | kubectl apply -f -</pre><p>Deploy all components required for the demonstration.</p><pre>$ make deploy-flagger-release ROUTING=header-based<br>$ kubectl apply -f deploy/book-svc.yaml<br>deployment.apps/book-svc created<br>service/book-svc created<br>Warning: annotation &quot;kubernetes.io/ingress.class&quot; is deprecated, please use &#39;spec.ingressClassName&#39; instead<br>ingress.networking.k8s.io/book-svc created</pre><h4>Configure A/B testing with Flagger</h4><pre>apiVersion: flagger.app/v1beta1<br>kind: Canary<br>metadata:<br>  name: book-svc<br>  namespace: test<br>spec:<br>  # ingress reference<br>  provider: nginx<br>  ingressRef:<br>    apiVersion: networking.k8s.io/v1<br>    kind: Ingress<br>    name: book-svc<br>  targetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: book-svc<br>  service:<br>    # container port<br>    port: 8080<br>  analysis:<br>    interval: 2m<br>    threshold: 10<br>    iterations: 20<br>    match:<br>      - headers:<br>          x-backend:<br>            exact: &quot;new&quot;<br>    metrics:<br>    - name: request-success-rate<br>      thresholdRange:<br>        min: 99<br>      interval: 1m<br>    - name: request-duration<br>      thresholdRange:<br>        max: 500<br>      interval: 30s</pre><p>We will discuss what we configured in the above YAML configuration:</p><p>The analysis section specifies the settings for canary analysis:</p><ul><li><strong>interval</strong>: Sets the interval for analysis to 2 minutes.</li><li><strong>threshold</strong>: Specifies the threshold for the canary analysis.</li><li><strong>iterations</strong>: 20: Defines the number of iterations for the canary analysis.</li><li><strong>match</strong>: Defines the criteria for matching requests to the canary version.<br>- <strong>headers</strong>: Specifies the HTTP headers to be matched.<br> — <strong>x-backend</strong>: Matches requests with the exact value “new” in the “x-backend” header.<br>- <strong>cookie</strong>: Matches requests with the exact value “canary” in the cookie.</li><li><strong>metrics</strong>: Includes metric checks for evaluating canary success:<br>- <strong>name</strong>: The metric being checked, like request success rate and request duration.<br>- <strong>thresholdRange</strong>: The acceptable range for the metric’s values.<br>- <strong>interval</strong>: The frequency of metric checks during analysis.</li></ul><p>In summary, the YAML configures the canary release to route traffic to the new version with the header and the older version without the header.</p><p>Apply it with the following command:</p><pre>kubectl apply -f flagger/header-based.yaml</pre><p>A fresh deployment named “deployment.apps/book-svc-primary” will be generated, containing the identical number of replicas as the “book-svc” deployment. After the new pods are operational, the original deployment is scaled down to zero. This establishes a deployment that Flagger manages as an underlying component.</p><pre>$ kubectl get deployments.apps -n test <br>NAME               READY   UP-TO-DATE   AVAILABLE   AGE<br>book-svc           0/0     0            0           1m<br>book-svc-primary   1/1     1            1           10m</pre><p>It creates a new canary object to check the status of the release. The status of the canary is initialized as of now before the rollout of the new release.</p><pre>$ kubectl get canaries -n test <br>NAME       STATUS        WEIGHT   LASTTRANSITIONTIME<br>book-svc   Initialized   0        2023-06-25T17:51:03Z</pre><p>It will also create the following services. book-svc-canary represents the canary version, and book-svc-primary denotes the primary version for the deployment created when we created the Flagger canary. These services enable Linkerd, guided by Flagger, to route traffic based on specified headers. Depending on the header conditions, incoming requests are routed to the appropriate version, ensuring a controlled transition between primary and canary versions during the release process.</p><pre>$ kubectl get svc -n test <br>NAME               TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE<br>book-svc           ClusterIP   10.96.99.39     &lt;none&gt;        8080/TCP   36m<br>book-svc-canary    ClusterIP   10.96.225.92    &lt;none&gt;        8080/TCP   18m<br>book-svc-primary   ClusterIP   10.96.219.233   &lt;none&gt;        8080/TCP   18m</pre><h4>Configure and deploy the load generator</h4><p>Edit env variables in deploy/load-generator.yaml.</p><ol><li>Modify ENDPOINT as “http://app.example.com” to generate external live traffic.</li><li>As we configured the header key as ‘x-backend’ and header value as ‘new’ in the above Flagger canary configuration, add it in the load generator environment variables so that the load generator can generate live traffic with the header ‘x-backend: new’ for the new release.</li></ol><pre>         env:<br>         - name: ENDPOINT<br>         value: &quot;http://app.example.com/&quot;<br>         - name: CALL_DURATION<br>         value: &quot;20&quot;<br>         - name: SLEEP_DURATION<br>         value: &quot;10&quot;<br>         - name: NEW_VERSION_HEADER_KEY<br>         value: &quot;x-backend&quot;<br>         - name: NEW_VERSION_HEADER_VAL<br>         value: &quot;new&quot;</pre><h4>Rollout new release</h4><p>Suppose that you have made some changes in the code or you have a new API version that needs to be rolled out. For this application, let’s say we have a new release build with version v1 with image book-svc:v1. We are changing the image to book-svc:v1 and the VERSION env variable to v1 with the patch file flagger/flagger-release-patch.json</p><p>Patch deployment book-svc for the new version of the application by running the following command:</p><pre>make patch-flagger-release</pre><p>We can see the status of the rollout by running:</p><pre>watch kubectl get canaries.flagger.app -n test</pre><p>We can check the response of the older version API with the following URL:</p><pre>http://app.example.com/</pre><p>This would return the following response:</p><pre>{<br>&quot;author&quot;: &quot;F. Scott Fitzgerald&quot;,<br>&quot;backend&quot;: &quot;book-svc&quot;,<br>&quot;genre&quot;: &quot;Fiction&quot;,<br>&quot;header&quot;: &quot;&quot;,<br>&quot;id&quot;: &quot;123456&quot;,<br>&quot;rating&quot;: 4.5,<br>&quot;status&quot;: &quot;success&quot;,<br>&quot;title&quot;: &quot;The Great Gatsby&quot;,<br>&quot;version&quot;: &quot;primary&quot;,<br>&quot;year&quot;: 1925<br>}</pre><h4>Response from the old version</h4><p>We can route to the new version of the application by passing x-backend: new header in the request as follows:</p><pre>curl -sX GET -H &#39;x-backend: new&#39; http://app.example.com/</pre><p>This would give us the following response:</p><pre>{<br>&quot;Publisher&quot;: &quot;Scribner&quot;,<br>&quot;author&quot;: &quot;F. Scott Fitzgerald&quot;,<br>&quot;backend&quot;: &quot;book-svc-v1&quot;,<br>&quot;genre&quot;: &quot;Fiction&quot;,<br>&quot;header&quot;: &quot;&quot;,<br>&quot;id&quot;: &quot;123456&quot;,<br>&quot;rating&quot;: {<br>&quot;average&quot;: 4.8,<br>&quot;totalVotes&quot;: 100<br>},<br>&quot;status&quot;: &quot;success&quot;,<br>&quot;summary&quot;: &quot;The Great Gatsby is a novel by F. Scott Fitzgerald...&quot;,<br>&quot;title&quot;: &quot;The Great Gatsby&quot;,<br>&quot;version&quot;: &quot;V1&quot;,<br>&quot;year&quot;: 1925<br>}</pre><h3>Monitor and analysis</h3><p>In order to monitor the A/B testing results, we can use the Linkerd viz feature. You must have already installed the Linkerd viz extension when setting up in the above steps.</p><h4>Evaluating the A/B test results based on predefined metrics and success criteria</h4><p>In order to say the test has been successful, we need to make sure that a certain number of requests pass the test. Since we are using Flagger to generate load for testing, we have set the success criteria to be 99%. If the success criteria are not met, then Flagger will stop the promotion of the service to the newer version. We can set the success criteria in the YAML files as shown above in the setup steps of flagger.yaml.</p><p>We also set a threshold of 10 which means that a maximum of 10 failures are allowed before rollback to the previous version happens. Once everything is set up and deployed, as mentioned in the above steps, we can go ahead with our analysis.</p><p>In order to view the stats through the CLI we can run the following command:</p><pre>linkerd viz -n test stat deploy --from deploy/load-generator</pre><p>This will give us the stats of the load that is being sent to both the services and its success rate.</p><pre>$ linkerd viz -n test stat deploy --from deploy/load-generator<br>NAME               MESHED   SUCCESS   RPS   LATENCY_P50   LATENCY_P95   LATENCY_P99   TCP_CONN<br>book-svc              1/1     100.00%     0.0rps         1ms          1ms             1ms          1<br>book-svc-primary      1/1     100.00%     1.0rps         1ms          5ms             5ms          1</pre><p>We use a load balancer to generate the load, which runs 20 iterations over a defined period of time and generates metrics based on it. In the above response, we can see its success rate and latency.</p><p>In order to visualize Linkerd UI, we can open Linkerd viz UI by running this command:</p><pre>linkerd viz dashboard &amp;</pre><p>We can see the HTTP and TCP metrics to get the success rate and decide which version performs better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LruNz_n1NR3yuQDd.png" /><figcaption>(Success rate to decide which version to keep)</figcaption></figure><h3>Conclusion</h3><p>In this blog post, we learned how to achieve A/B testing using Flagger. We went through understanding how to implement A/B testing. Later on, we discussed how to monitor the tests and also did an analysis using the Linkerd viz extension.</p><p>Overall, the analysis of A/B testing using Linkerd’s dynamic request routing feature provides valuable insights into the test’s success, load distribution, and gradual traffic shift during canary deployments. You can follow this article to do A/B testing, however, in a real-world scenario, things could be complicated. For that, you can bring in <a href="https://www.infracloud.io/progressive-delivery-consulting/">Progressive Delivery experts</a> onboard to help you out.</p><p>Thanks for reading this blog post. We hope it was informative and engaging for you. We would love to hear your thoughts on this post, so start a conversation on LinkedIn — <a href="https://www.linkedin.com/in/hitesh-wani-6a7103138/">Hitesh Wani</a> and <a href="https://www.linkedin.com/in/pranoy-kundu/">Pranoy Kundu</a>.</p><h3>References</h3><ul><li><a href="https://www.cncf.io/blog/2022/07/21/keep-calm-and-trust-a-b-testing-with-flux-flagger-and-linkerd/">A/B testing, Flagger and Linkerd</a></li><li><a href="https://docs.flagger.app/tutorials/linkerd-progressive-delivery#a-b-testing">Linkerd progressive delivery: A/B testing</a></li><li><a href="https://linkerd.io/2.13/tasks/flagger/">Progressive delivery with Flagger</a></li><li><a href="https://buoyant.io/media/rapid-experimentation-simplified-with-linkerd">Rapid experimentation simplified with Linkerd</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f3eae052a0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/infracloud-technologies/a-b-testing-with-linkerd-and-flagger-using-dynamic-routing-0f3eae052a0d">A/B Testing with Linkerd and Flagger using Dynamic Routing</a> was originally published in <a href="https://medium.com/infracloud-technologies">InfraCloud Technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New functions to support sync.Once]]></title>
            <link>https://medium.com/@pranoy1998k/new-functions-to-support-sync-once-5c1f6744ac2e?source=rss-3714d8983989------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c1f6744ac2e</guid>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pranoy Kundu]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 12:32:48 GMT</pubDate>
            <atom:updated>2023-10-02T12:36:35.010Z</atom:updated>
            <content:encoded><![CDATA[<p>Go 1.21 added 3 new functions in the sync package. OnceFunc, OnceValue, and OnceValues. They capture common use cases of Once to lazily initialize a value on first use. Internally all of these functions use the sync.Once to perform the task.</p><h3>Let us first have a look at the classic sync.Once</h3><p>sync.Once is a type, unlike OnceFunc, OnceValue or OnceValues. Once is an object that will perform only one action. This type has only one method `Do` in it.</p><p>In order to perform an action only once we need to make use of the Do method. Do will call a function f if and only if it’s been called for the first time. In order to call the function f<em> </em>again with different values a new instance of Once is required.</p><p>Function f must be niladic in order to invoke a Do function, so if you want to pass the arguments you might need a function literal.</p><pre>package main<br><br>import (<br>   &quot;fmt&quot;<br>   &quot;sync&quot;<br>)<br><br>type BookKeeper struct {<br>   name        string<br>   id          string<br>   phoneNumber string<br>}<br><br>func NewBookKeeper(name, id, phoneNumber string) *BookKeeper {<br>   fmt.Printf(&quot;NewBookKeeper name: %s, id: %s, phoneNumber: %s\n&quot;, name, id, phoneNumber)<br>   return &amp;BookKeeper{<br>       name:        name,<br>       id:          id,<br>       phoneNumber: phoneNumber,<br>   }<br>}<br><br>func main() {<br>   var once sync.Once<br>   done := make(chan bool)<br>   var bk *BookKeeper<br>   for i := 0; i &lt; 5; i++ {<br>       go func() {<br>           once.Do(func() { bk = NewBookKeeper(&quot;John&quot;, &quot;123456789&quot;, &quot;1234567890&quot;) })<br>           done &lt;- true<br>       }()<br>   }<br><br>   for i := 0; i &lt; 5; i++ {<br>       &lt;-done<br>   }</pre><p>In the above example we ensure that the bookkeeper is initialized only once even if it is called multiple times.</p><h3>sync.OnceFunc</h3><pre>func OnceFunc(f func()) func()</pre><p>OnceFunc returns a function f that invokes only once. You can also call the returned function concurrently.</p><p>The function f must again be niladic only and also shouldn’t return any value.</p><pre>func helloWorld() {<br>   fmt.Println(&quot;Hello World!&quot;)<br>}<br><br>func main() {<br>   once := sync.OnceFunc(helloWorld)<br>   for i := 0; i &lt; 5; i++ {<br>       once()<br>   }<br>}</pre><p>In the above example, even if once() is being called multiple times it is invoked only once.</p><h3>sync.OnceValue</h3><pre>func OnceValue[T any](f func() T) func() T</pre><p>Using OnceValue we can invoke function f only once and returns the value returned by f. You can also call the returned function concurrently. Function f should again be niladic only.</p><pre>type BookKeeper struct {<br>   name        string<br>   id          string<br>   phoneNumber string<br>}<br><br>func NewBookKeeper(name, id, phoneNumber string) *BookKeeper {<br>   return &amp;BookKeeper{<br>       name:        name,<br>       id:          id,<br>       phoneNumber: phoneNumber,<br>   }<br>}<br><br>func (bk *BookKeeper) getName() string {<br>   return bk.name<br>}<br><br>func main() {<br>   bk :=  NewBookKeeper(&quot;John&quot;, &quot;123456789&quot;, &quot;1234567890&quot;)<br><br>   onceValue := sync.OnceValue[string](bk.getName)<br>   for i := 0; i &lt; 5; i++ {<br>       fmt.Println(onceValue())<br>   }<br>}</pre><p>In the above example, onceValue is invoked only once and its value is stored. So, if OnceValue is being called multiple times it is invoked only once and its value is returned on subsequent calls.</p><p>You can only use OnceValue in case your function returns only one value.</p><h3>sync.OnceValues</h3><pre>func OnceValues[T1, T2 any](f func() (T1, T2)) func() (T1, T2)</pre><p>OnceValues helps in returning two values from the function. Its behavior is similar to that of OnceValue where a function is invoked once and it’s values are stored. On subsequent calls, the stored values are returned. You can also call the returned function concurrently.</p><p>Once values come in handy in cases where you want to invoke functions that return a value and an error only.</p><pre>package main<br><br>import (<br>   &quot;fmt&quot;<br>   &quot;sync&quot;<br>)<br><br>type BookKeeper struct {<br>   name        string<br>   id          string<br>   phoneNumber string<br>}<br><br>func NewBookKeeper(name, id, phoneNumber string) *BookKeeper {<br>   return &amp;BookKeeper{<br>       name:        name,<br>       id:          id,<br>       phoneNumber: phoneNumber,<br>   }<br>}<br><br>func (bk *BookKeeper) getNameAndPhoneNumber() (string, string) {<br>   return bk.name, bk.phoneNumber<br>}<br><br>func main() {<br>   bk :=  NewBookKeeper(&quot;John&quot;, &quot;123456789&quot;, &quot;1234567890&quot;)<br><br>   onceValues := sync.OnceValues[string, string](bk.getNameAndPhoneNumber)<br>   for i := 0; i &lt; 5; i++ {<br>       fmt.Println(onceValues())<br>   }<br>}</pre><p>In all the the above 3 Once functions if function f panics, the returned function will panic with the same value on every call.</p><p>I have also tried to benchmark and check on their performance but it looks like there is no significant difference in their performance. Results can be found here <a href="https://github.com/pranoyk/understanding-go-sync-package/blob/main/synconce/test.out">https://github.com/pranoyk/understanding-go-sync-package/blob/main/synconce/test.out</a>.</p><h3>Conclusion</h3><ol><li>OnceFunc, OnceValue and OnceValues functions are created in order to capture the common use cases of Once.Do methods</li><li>They do not provide any significant performance enhancements over Once.Do</li><li>Although they do take out some boilerplate code to initialize Once and call Do method.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c1f6744ac2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>