Sub topic 7
Informers and caches: reading without hammering the API server
This chapter assumes you know the control loop pattern, the List and Watch calls, and basic Go. A controller needs to read objects constantly. If every reconcile pass sent a GET to the API server, a cluster with thousands of Pods would overload it. Informers solve this by keeping a local copy of the objects the controller cares about.
What an informer does
An informer is a client-side component that mirrors one resource type from the API server into memory. It has four parts:
- Reflector: runs one List, then a Watch from the returned resource version. It re-lists if the watch breaks and the resume point is too old.
- DeltaFIFO: a queue of changes (added, updated, deleted) coming from the reflector.
- Indexer: the local store. It holds the latest copy of each object and supports lookups by namespace, name, or a custom index such as node name.
- Event handlers: callbacks that run after the store is updated. Controllers use them to push object keys onto a work queue.
Shared informers
A process often has several controllers that need Pods. A shared informer factory creates one informer per resource type and gives every controller the same cache. This means one watch connection and one copy in memory, however many handlers register.
package main
import (
"fmt"
"os"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
cfg, err := clientcmd.BuildConfigFromFlags("", os.Getenv("KUBECONFIG"))
if err != nil {
panic(err)
}
client, err := kubernetes.NewForConfig(cfg)
if err != nil {
panic(err)
}
factory := informers.NewSharedInformerFactory(client, 10*time.Minute)
podInformer := factory.Core().V1().Pods().Informer()
podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pod := obj.(*corev1.Pod)
fmt.Println("seen:", pod.Namespace+"/"+pod.Name)
},
})
stop := make(chan struct{})
defer close(stop)
factory.Start(stop)
if !cache.WaitForCacheSync(stop, podInformer.HasSynced) {
panic("cache did not sync")
}
pods, err := factory.Core().V1().Pods().Lister().Pods("default").List(labels.Everything())
if err != nil {
panic(err)
}
fmt.Println("pods in default:", len(pods))
}Set KUBECONFIG to a valid kubeconfig path before running. The lister reads from memory and makes no API call. The 10-minute argument is the resync period, which replays cached objects to handlers. It does not re-fetch anything from the server.
Common errors
- Reading before the cache has synced. An empty cache looks like "nothing exists", and a controller may then create duplicates. Always wait for
HasSynced. - Mutating cached objects. Listers return pointers to the shared copy. Call
DeepCopy()before changing anything, or you corrupt every other reader. - Expecting read-your-writes. After you create an object, the cache may not show it for a short time. A reconcile that looks it up immediately may create it twice. Idempotent logic and conflict errors catch this case.
- Caching too much. The cache holds every object of the type. Restrict it with namespaces or label selectors on large clusters.
Exercise
Your reconcile function creates a ConfigMap, and on the next pass it looks the ConfigMap up through the cached client and does not find it. What happened, and how should the code respond?
Show answer
The cache has not yet received the watch event for the new ConfigMap, so it is briefly stale. The code should treat the create as idempotent: if the create returns AlreadyExists, or a later pass finds the object, it carries on without error. It should not assume the cache is current.