Operating, scaling and debugging · 7 MIN READ
Talk to the Kubernetes API from Go with client-go, informers and workqueues
Build a clientset from in-cluster or kubeconfig credentials, watch objects through a shared informer and lister, reconcile keys from a rate-limited workqueue, and shut a Go service down cleanly on SIGTERM.
Every controller in a cluster, including the one that runs Deployments, is a Go program built on client-go. A loop that calls List every few seconds overloads the API server and still misses short-lived changes. Informers, listers and workqueues let a controller react to every change from a local cache while its load on the API server stays small and bounded.
kubernetes · A MAP OF THE IDEA
- rest.Config and clientset
- Shared informer and lister
- Handlers enqueue keys
- Workers reconcile from cache
Useful when
- One watch per resource type serves every handler in the process.
- Level-triggered reconcile recovers from missed events and restarts.
Watch out
- Modifying a cached object corrupts what every other reader sees.
- Two replicas without leader election fight over the same objects.
Implementation & operation cost: A few hundred lines of Go per controller, or controller-runtime as a dependency, plus RBAC for everything it watches.
Config, clientset and rate limits
A rest.Config holds the API server address, the credentials and the client's limits. Inside a pod, rest.InClusterConfig reads the ServiceAccount token and CA from /var/run/secrets/kubernetes.io/serviceaccount and the KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT variables; outside, clientcmd loads a kubeconfig the way kubectl does. kubernetes.NewForConfig returns a typed clientset: cs.AppsV1().Deployments(ns).Get(ctx, name, metav1.GetOptions{}) returns an *appsv1.Deployment. The dynamic client handles any resource as unstructured data, which suits CRDs without generated types. client-go limits itself to 5 requests per second with bursts of 10 unless you raise QPS and Burst, and the API server adds API Priority and Fairness, answering 429 when a client floods it. Use the client-go minor version that matches the cluster: v0.34 for Kubernetes 1.34.
func newClientset(kubeconfig string) (*kubernetes.Clientset, error) {
cfg, err := rest.InClusterConfig()
if errors.Is(err, rest.ErrNotInCluster) {
cfg, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
}
if err != nil {
return nil, err
}
cfg.QPS, cfg.Burst = 20, 40
cfg.UserAgent = "web-controller"
return kubernetes.NewForConfig(cfg)
}The function prefers in-cluster credentials and falls back to a kubeconfig file only when the process is not running in a pod, so the same binary works in both places. Raising QPS and Burst suits a controller that starts with many reads, and a UserAgent makes its requests recognisable in API server audit logs and metrics.
From List and Watch to shared informers
A List returns a snapshot with a resourceVersion, and a Watch from that version streams ADDED, MODIFIED and DELETED events. Watches end on timeouts, and a version that is too old gets 410 Gone, so a correct client relists and watches again without losing changes. An informer does exactly that and keeps an indexed local cache. A SharedInformerFactory shares one List and Watch per resource type among every handler in the process, and a lister reads from the cache without any API call. Handlers must return quickly and should only enqueue a key. Objects in the cache are shared: never modify them, DeepCopy first. Start the factory and wait for the caches to sync before doing work, or the controller acts on an empty view of the cluster.
factory := informers.NewSharedInformerFactory(cs, 10*time.Minute)
deployments := factory.Apps().V1().Deployments()
lister := deployments.Lister()
queue := workqueue.NewTypedRateLimitingQueue(
workqueue.DefaultTypedControllerRateLimiter[string]())
enqueue := func(obj any) {
if key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj); err == nil {
queue.Add(key)
}
}
deployments.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: enqueue,
UpdateFunc: func(_, obj any) { enqueue(obj) },
DeleteFunc: enqueue,
})
factory.Start(ctx.Done())
for typ, synced := range factory.WaitForCacheSync(ctx.Done()) {
if !synced {
return fmt.Errorf("cache for %v did not sync", typ)
}
}The ten-minute resync period re-delivers every cached object as an update, a safety net for side effects that went missing. DeletionHandlingMetaNamespaceKeyFunc also handles the tombstone a handler receives when a delete happened while the watch was down. Keys are namespace/name strings such as default/web, so the queue holds names, never stale copies of objects.
The workqueue and the reconcile loop
The workqueue sits between handlers and workers. It deduplicates, so ten updates to default/web while the key waits become one reconcile, and it never hands one key to two workers at once. Reconcile is level-triggered: it ignores what the event said, reads the current object from the lister, compares desired with actual state and takes one step towards desired. NotFound from the lister means the object was deleted. On error the key goes back with AddRateLimited, using per-item exponential backoff from 5 ms to 1000 s under an overall limit of 10 per second; on success Forget resets that backoff. Run several workers in goroutines, and when the controller has more than one replica, use leader election on a Lease so that only one of them acts.
func runWorker(ctx context.Context, queue workqueue.TypedRateLimitingInterface[string], lister appslisters.DeploymentLister) {
for {
key, shutdown := queue.Get()
if shutdown {
return
}
if err := reconcile(ctx, lister, key); err != nil {
queue.AddRateLimited(key)
} else {
queue.Forget(key)
}
queue.Done(key)
}
}
func reconcile(ctx context.Context, lister appslisters.DeploymentLister, key string) error {
ns, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return nil
}
d, err := lister.Deployments(ns).Get(name)
if apierrors.IsNotFound(err) {
return nil // deleted: clean up whatever you created for it
}
if err != nil {
return err
}
if d.Status.ReadyReplicas < *d.Spec.Replicas {
log.Printf("%s: %d of %d ready", key, d.Status.ReadyReplicas, *d.Spec.Replicas)
}
return nil
}Done must follow every Get, or the key stays marked as in progress and is never processed again. A malformed key returns nil because retrying cannot fix it. This reconcile only reports Deployments with fewer ready replicas than desired; a real controller would create, update or delete objects at that point, always computing the change from the current state.
controller-runtime, operators and CRDs
Writing informers, queues and leader election by hand teaches how controllers work, but most new controllers use controller-runtime. Its Manager owns a shared cache, clients, leader election, metrics and health endpoints; you implement Reconcile(ctx, req) (ctrl.Result, error) for one key and declare which objects trigger it. Kubebuilder and the Operator SDK scaffold such projects, generate CRD manifests and RBAC rules from Go markers, and add webhooks. A CustomResourceDefinition adds a new resource type to the API server, such as kind: Website, with an OpenAPI v3 schema that validates objects, one or more versions, and a status subresource that the controller writes. The API server stores and serves these objects; a controller gives them behaviour. A CRD plus a controller that encodes operational knowledge, such as backups or failover, is called an operator.
Graceful shutdown on SIGTERM
When a pod is deleted by a rollout, a drain or a scale-down, the kubelet runs the preStop hook, sends SIGTERM to the container's main process, and sends SIGKILL when terminationGracePeriodSeconds runs out: 30 by default, counted from the start of preStop. At the same moment the pod leaves the EndpointSlices, and kube-proxy and ingress controllers need a few seconds to notice, so new requests still arrive. A short preStop sleep covers that window; the sleep action is stable in Kubernetes 1.34 and needs no sleep binary in the image. Then the Go process stops accepting connections and finishes in-flight requests with http.Server.Shutdown, within the grace period that remains. Make the Go binary PID 1 with the exec form of ENTRYPOINT; the shell form runs sh -c as PID 1, which often does not pass SIGTERM on.
func serve(srv *http.Server) error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
errc := make(chan error, 1)
go func() { errc <- srv.ListenAndServe() }()
select {
case err := <-errc:
return err
case <-ctx.Done():
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
return srv.Shutdown(shutdownCtx)
}signal.NotifyContext cancels ctx on SIGTERM. Shutdown closes the listeners, waits for active requests and returns when they finish or after 20 seconds, inside a 30-second grace period that already spent 5 seconds in preStop. A controller shuts down the same way: cancelling its context stops the informers, queue.ShutDown ends the workers, and leader election with ReleaseOnCancel hands over the Lease at once.
Try it in the lab terminal
Watch the Deployment and ReplicaSet controllers run the loop described above. Follow the owner references from pod to ReplicaSet to Deployment, change the desired state with scale, destroy actual state by deleting the pods and then the ReplicaSet, and read the events each controller records as it converges. This is the loop your own controller would implement: observe, compare, act, repeat.
kind create cluster
kubectl create deployment web --image=gopherforge/web:v2 --replicas=2
kubectl rollout status deploy/web
kubectl get pods -o custom-columns=POD:.metadata.name,OWNER-KIND:.metadata.ownerReferences[0].kind,OWNER:.metadata.ownerReferences[0].name
kubectl get rs -o jsonpath='{.items[0].metadata.ownerReferences[0].kind}/{.items[0].metadata.ownerReferences[0].name}{"\n"}'
kubectl scale deploy/web --replicas=4
kubectl get rs
kubectl delete pod -l app=web
kubectl get rs
kubectl wait --for=condition=Ready pod -l app=web --timeout=60s
kubectl get events --sort-by=.lastTimestamp | grep -E 'ScalingReplicaSet|SuccessfulCreate'
kubectl delete rs -l app=web
cluster tick 10s
kubectl get rs,podscustom-columns shows each pod owned by ReplicaSet web-<hash>, and the jsonpath shows that ReplicaSet owned by Deployment/web. After the scale, get rs shows DESIRED 4, CURRENT 4, READY 2. After all four pods are deleted, READY is 0 but CURRENT is already 4 again. The events show both controllers at work: ScalingReplicaSet "from 2 to 4" from the Deployment controller, then six SuccessfulCreate events from the ReplicaSet controller, four of them after the delete. Even a deleted ReplicaSet comes back: the Deployment controller recreates it under the same name, a hash of the pod template, and ten seconds later it has four Running pods.
TAKE THIS WITH YOU
Build controllers from a shared informer, a lister and a rate-limited workqueue, and reconcile each key from the current state, not from the event. On SIGTERM, drain in-flight work before the grace period ends.
Check your understanding
Your controller calls Deployments(ns).List on the API server in every reconcile and is throttled with 429 responses as the cluster grows. Where should reconcile read Deployments from instead?
Go to the source
Progress stays in this browser. No account needed.