TExcelTAD
Home › GitOps: Argo CD & Flux › The Reconcile Loop, Modelled

The Reconcile Loop, Modelled

Argo CD and Flux look very different from the outside, but at their core both run the same loop that every Kubernetes controller runs:

text
forever:
    desired = fetch and render the source (Git commit -> plain manifests)
    live    = read the matching objects from the cluster
    diff    = compare(desired, live)
    if diff is not empty and policy allows:
        apply the difference
    report status (Synced / OutOfSync, Healthy / Progressing / Degraded)
    wait for the next interval or event

Understanding this loop explains almost every GitOps behaviour you will meet: why a manual kubectl edit disappears, why a deleted file deletes a Deployment, why an HPA and a GitOps agent can fight, and why a broken manifest freezes a whole application. This lesson builds the loop in Python, step by step.

Three inputs, not two

Comparing Git with the cluster isn't enough. Suppose the cluster has a CronJob/cleanup that Git doesn't mention. Should the agent delete it? Only if the agent created it in the first place; otherwise it might be someone else's object (a cert-manager Secret, a Pod created by a Job). So an agent tracks a third set: what it manages.

  • Argo CD marks objects it applied with a tracking annotation, argocd.argoproj.io/tracking-id (annotation tracking is the default since Argo CD 3.0; older installs used the app.kubernetes.io/instance label).
  • Flux's kustomize-controller labels them kustomize.toolkit.fluxcd.io/name and …/namespace, and keeps an inventory of applied objects in the Kustomization's status.

Version 1: one pass

python · try it yourself
def reconcile(desired, live, managed, prune=True):
    """Return the actions one pass would take, in a stable order."""
    actions = []
    for key in sorted(desired):
        if key not in live:
            actions.append(("create", key))
        elif live[key] != desired[key]:
            changed = sorted(k for k in desired[key] if live[key].get(k) != desired[key][k])
            actions.append(("patch", key, changed))
    for key in sorted(live):
        if key not in desired and key in managed:
            actions.append(("delete" if prune else "orphan", key))
    return actions

desired = {
    "ConfigMap/linkly-config": {"LOG_LEVEL": "info"},
    "Deployment/linkly": {"image": "linkly:1.4.0", "replicas": 2},
    "Service/linkly": {"port": 80},
}
live = {
    "Deployment/linkly": {"image": "linkly:1.3.2", "replicas": 2},
    "Service/linkly": {"port": 80},
    "CronJob/cleanup": {"schedule": "0 3 * * *"},        # removed from Git last week
    "Secret/linkly-db": {"url": "(encrypted)"},           # created by another tool
}
managed = {"Deployment/linkly", "Service/linkly", "CronJob/cleanup"}

for action in reconcile(desired, live, managed):
    print(*action)
print("--- with prune disabled:")
for action in reconcile(desired, live, managed, prune=False):
    print(*action)
create ConfigMap/linkly-config
patch Deployment/linkly ['image']
delete CronJob/cleanup
--- with prune disabled:
create ConfigMap/linkly-config
patch Deployment/linkly ['image']
orphan CronJob/cleanup

Secret/linkly-db is never touched: it is not in Git and not managed. CronJob/cleanup is managed but gone from Git, so with pruning on it is deleted; with pruning off it is left behind as an orphan (both tools default to not pruning in some form, which you will see later).

Version 2: a loop over time

Real agents run the pass again and again. This model replays a fixed timeline: commits arrive in Git, a person runs kubectl scale, and the agent ticks every interval. Two policy switches decide what happens to drift:

  • auto-sync: when Git changes, apply it without waiting for a human to press Sync;
  • self-heal: when the cluster changes (Git did not), revert it.
python · try it yourself
def diff(desired, live, managed):
    out = []
    for key in sorted(desired):
        if live.get(key) != desired[key]:
            out.append(("apply", key))
    for key in sorted(live):
        if key not in desired and key in managed:
            out.append(("prune", key))
    return out

def run(timeline, auto_sync=True, self_heal=True, prune=True):
    git, live, managed = {}, {}, set()
    last_synced_commit = None
    for tick, event in timeline:
        kind, payload = event if event else (None, None)
        if kind == "commit":
            git = payload["state"]
            commit = payload["sha"]
        elif kind == "kubectl":
            key, value = payload
            live[key] = value
        todo = diff(git, live, managed)
        status = "Synced" if not todo else "OutOfSync"
        new_commit = commit != last_synced_commit
        if todo and auto_sync and (new_commit or self_heal):
            for verb, key in todo:
                if verb == "apply":
                    live[key] = dict(git[key]); managed.add(key)
                elif prune:
                    del live[key]; managed.discard(key)
            last_synced_commit = commit
            note = ", ".join(f"{v} {k}" for v, k in todo if v == "apply" or prune)
            status = f"OutOfSync -> synced ({note})"
        print(f"t={tick:>2}  {(kind or '-'):8} {status}")
    return live

v1 = {"Deployment/linkly": {"image": "1.4.0", "replicas": 2}, "ConfigMap/linkly": {"LOG_LEVEL": "info"}}
v2 = {"Deployment/linkly": {"image": "1.5.0", "replicas": 2}}
timeline = [
    (0, ("commit", {"sha": "a1", "state": v1})),
    (3, None),
    (6, ("kubectl", ("Deployment/linkly", {"image": "1.4.0", "replicas": 5}))),
    (9, None),
    (12, ("commit", {"sha": "b2", "state": v2})),
]
print("auto-sync + self-heal:")
run(timeline)
print("auto-sync only:")
live = run(timeline, self_heal=False)
print("final replicas:", live["Deployment/linkly"]["replicas"])
auto-sync + self-heal:
t= 0  commit   OutOfSync -> synced (apply ConfigMap/linkly, apply Deployment/linkly)
t= 3  -        Synced
t= 6  kubectl  OutOfSync -> synced (apply Deployment/linkly)
t= 9  -        Synced
t=12  commit   OutOfSync -> synced (apply Deployment/linkly, prune ConfigMap/linkly)
auto-sync only:
t= 0  commit   OutOfSync -> synced (apply ConfigMap/linkly, apply Deployment/linkly)
t= 3  -        Synced
t= 6  kubectl  OutOfSync
t= 9  -        OutOfSync
t=12  commit   OutOfSync -> synced (apply Deployment/linkly, prune ConfigMap/linkly)
final replicas: 2

Read the second run carefully. With self-heal off, the manual scale to 5 stays and the app sits OutOfSync (the tool reports the drift, but doesn't fix it). The scale is only overwritten at t=12, as a side effect of an unrelated commit: a surprise for whoever made it, and a classic incident pattern. That is why teams turn self-heal on, or make sure nothing is changed by hand.

What real agents add

The model leaves out several things the real controllers do, each covered later:

Real behaviour Where it's taught
render the source first (Helm, Kustomize, plain YAML) Declarative State in Git
compare only fields Git sets, ignore defaults and fields owned by others (HPA replicas) Drift, Self-Heal & Prune
apply in order: namespaces and CRDs first, then waves Sync Waves & Hooks
wait for health, not just "applied" Health Checks
retry failed syncs with backoff, and don't retry the same failed commit forever Sync Policies
react to events (webhook from Git, watch on the cluster) instead of only polling Argo CD Architecture, Flux

Both tools poll Git on an interval (Argo CD's default is about three minutes; Flux uses the interval you set on each source) and can be woken earlier by a webhook. They also watch the cluster, so drift is noticed within seconds, not at the next poll.

Test yourself

Why does a GitOps agent track which objects it manages, instead of deleting everything in the namespace that isn't in Git?

  1. For performance
  2. Objects created by other controllers or people would otherwise be deleted by pruning
  3. Kubernetes requires it
  4. To support Helm

In the timeline model with auto-sync on and self-heal off, what happens to a manual kubectl scale to 5 replicas?

  1. It is reverted within seconds
  2. The app is reported OutOfSync and the change stays until the next sync, e.g. after a new commit
  3. The agent deletes the Deployment
  4. Git is updated to 5 replicas

What is the 'desired state' an agent compares with the cluster?

  1. The Helm chart source files
  2. The manifests rendered from the source at a specific commit
  3. The last state it applied
  4. The CI pipeline definition