<p>I want to watch changes to Pods continuously using the client-go Kubernetes SDK. I am using the below code to watch the changes:</p>
<pre class="lang-golang prettyprint-override"><code>func (c *Client) watchPods(namespace string, restartLimit int) {
    fmt.Println(&quot;Watch Kubernetes Pods&quot;)
    watcher, err := c.Clientset.CoreV1().Pods(namespace).Watch(context.Background(),
        metav1.ListOptions{
            FieldSelector: &quot;&quot;,
        })
    if err != nil {
        fmt.Printf(&quot;error create pod watcher: %v\n&quot;, err)
        return
    }

    for event := range watcher.ResultChan() {
        pod, ok := event.Object.(*corev1.Pod)
        if !ok || !checkValidPod(pod) {
            continue
        }
        owner := getOwnerReference(pod)
        for _, c := range pod.Status.ContainerStatuses {
            if reflect.ValueOf(c.RestartCount).Int() &gt;= int64(restartLimit) {
                if c.State.Waiting != nil &amp;&amp; c.State.Waiting.Reason == &quot;CrashLoopBackOff&quot; {
                    doSomething()
                }
                if c.State.Terminated != nil {
                    doSomethingElse()
                }
            }
        }
    }
}
</code></pre>
<p>The code is watching changes to the Pods, but it exits after some time. I want to run this continuously. I also want to know how much load it puts on the API Server and what is the best way to run a control loop for looking for changes.</p>

<p>In Watch, a long poll connection is established with the API server. Upon establishing a connection, the API server sends an initial batch of events and any subsequent changes. The connection will be dropped after a timeout occurs.</p>
<p>I would suggest using an Informer instead of setting up a watch, as it is much more optimized and easier to setup. While creating an informer, you can register specific functions which will be invoked when pods get created, updated and deleted. Even in informers you can target specific pods using a labelSelector, similar to watch. You can also create shared informers, which are shared across multiple controllers in the cluster. This results in reducing the load on the API server.</p>
<p>Below are few links to get you started:</p>
<ol>
<li><a href="https://aly.arriqaaq.com/kubernetes-informers/" rel="nofollow noreferrer">https://aly.arriqaaq.com/kubernetes-informers/</a></li>
<li><a href="https://www.cncf.io/blog/2019/10/15/extend-kubernetes-via-a-shared-informer/" rel="nofollow noreferrer">https://www.cncf.io/blog/2019/10/15/extend-kubernetes-via-a-shared-informer/</a></li>
<li><a href="https://pkg.go.dev/k8s.io/client-go/informers" rel="nofollow noreferrer">https://pkg.go.dev/k8s.io/client-go/informers</a></li>
</ol>
