Sub topic 10
Writing reconcile logic that is safe to repeat
This chapter assumes you know Pods, Deployments and kubectl, and can read simple Go. It also assumes you have met the Reconcile function from the previous chapter.
Why repetition is guaranteed
A controller does not run once per change. It runs whenever the work queue hands it a key. That can happen after a watch event, after a periodic resync, after an error retry, or after a restart. The same object may be reconciled many times with no change in between.
An operation is idempotent if running it once or many times leaves the system in the same final state. Reconcile must be idempotent, because you cannot control how often it is called.
Describe the end state, not the steps
The toy loop below shows the idea. It compares actual to desired and moves one step. Extra passes change nothing once the two match.
package main
import "fmt"
func main() {
desired := 3
actual := 0
for i := 0; i < 6; i++ {
if actual < desired {
actual++
} else if actual > desired {
actual--
}
fmt.Printf("pass %d: actual=%d desired=%d\n", i+1, actual, desired)
}
}Passes 4 to 6 print the same line as pass 3. That is idempotence.
Compare two ways to write the same intent:
| Edge-style (unsafe) | Level-style (safe) |
|---|---|
| "Create one Pod" | "Make sure 3 Pods exist" |
| "Append a rule" | "Make the rule list equal this list" |
| "Add 1 to a counter" | "Set the counter to the observed count" |
The left column breaks when repeated. Run it twice and you have two Pods.
Patterns that make reconcile safe
- Read current state first. Fetch the object, and treat not-found as success, since it was deleted.
- Create or update, never blindly create. An "already exists" error on a second pass is a bug.
- Use deterministic names. Derive child names from the parent, such as
defaultsin the parent's namespace, so a retry finds the existing child. - Compare before writing. Skip the write if nothing differs. This avoids needless API calls and avoid triggering new watch events.
- Do not store progress in memory. After a restart the controller has no memory. Everything it needs must be in the API objects.
The reconciler below follows these rules. CreateOrUpdate reads the ConfigMap, applies your mutation, and writes only if the result differs.
package controllers
import (
"context"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
type NamespaceDefaultsReconciler struct {
client.Client
}
func (r *NamespaceDefaultsReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var ns corev1.Namespace
if err := r.Get(ctx, req.NamespacedName, &ns); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
if !ns.DeletionTimestamp.IsZero() {
return ctrl.Result{}, nil
}
cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "defaults", Namespace: ns.Name}}
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, cm, func() error {
cm.Data = map[string]string{"managed-by": "namespace-defaults"}
return nil
})
return ctrl.Result{}, err
}Seeing it work
Delete the Pods of a Deployment and the ReplicaSet controller reconciles again. It sees fewer Pods than spec.replicas and creates replacements, with no special case for "Pods were deleted".
kubectl create deployment web --image=nginx:1.27 --replicas=3
kubectl get pods -l app=web -w &
kubectl delete pod -l app=web --wait=false
kubectl get replicaset -l app=webCommon mistakes
- Generating random names for children, which creates a new child on every pass.
- Failing on "already exists" instead of fetching and updating.
- Keeping a counter or "done" flag in a struct field.
- Writing an unchanged object, which can cause a loop of self-triggered reconciles.
Exercise
A reconciler creates a Pod named with a random suffix whenever it sees a Foo object with no Pod in its local list. The controller crashes after creating the Pod but before the cache updates, then restarts. What can go wrong, and how do you fix it?
Show answer
After the restart, the stale cache may show no Pod, so the reconciler creates a second Pod with a different random name. Fix it by using a deterministic name derived from the Foo, so the second create returns "already exists" and the reconciler fetches the existing Pod, or by using CreateOrUpdate. Also treat "already exists" as a signal to continue, not as a failure.