TExcelTAD
Home › GitOps: Argo CD & Flux › Sync Waves & Hooks

Sync Waves & Hooks

kubectl apply -f dir/ sends everything at once and hopes for the best. Real apps need order: the database migration must finish before the new code starts, the CRD must exist before its custom resources, the Secret before the Deployment that reads it. Argo CD solves this with phases, waves and hooks, all set by annotations on the objects themselves.

Phases and hooks

A sync runs in phases. Ordinary objects belong to the Sync phase; objects annotated as hooks run in the others:

Annotation argocd.argoproj.io/hook: Runs
PreSync before the manifests are applied (migrations, backups); a failure stops the sync
Sync together with the normal objects, after PreSync succeeded
PostSync after all Sync objects are applied and Healthy (smoke tests, notifications)
SyncFail when the sync fails (cleanup, alerting)
PostDelete after the Application's objects are deleted
Skip never applied by Argo CD

Hooks are usually Jobs. argocd.argoproj.io/hook-delete-policy says when to remove the finished hook: HookSucceeded, HookFailed, or BeforeHookCreation (the default: delete the old one just before creating the next).

Helm charts' own hooks are translated: helm.sh/hook: pre-install / pre-upgrade → PreSync, post-install / post-upgrade → PostSync, and helm.sh/hook-weight → sync wave. Rollback, delete and helm test hooks are handled differently or not at all (the Helm page of the Argo CD docs has the current table), so check charts that depend on them.

Waves

Inside a phase, argocd.argoproj.io/sync-wave: "<integer>" orders objects; the default is "0" and negative waves run earlier. Argo CD applies the lowest wave that still has out-of-sync or unhealthy objects, waits until that wave is healthy, pauses briefly (2 seconds by default, ARGOCD_SYNC_WAVE_DELAY) and moves on. Within one wave, objects are ordered by kind (Namespaces first, then things like ServiceAccounts, ConfigMaps and Services, then workloads, with custom resources last) and then by name.

The ordering, modelled

python · try it yourself
KIND_ORDER = ["Namespace", "ServiceAccount", "Secret", "ConfigMap", "CustomResourceDefinition",
              "ClusterRole", "Service", "Deployment", "StatefulSet", "Job", "HorizontalPodAutoscaler"]
PHASES = ["PreSync", "Sync", "PostSync"]

def sort_key(obj):
    kind_rank = KIND_ORDER.index(obj["kind"]) if obj["kind"] in KIND_ORDER else len(KIND_ORDER)  # CRs last
    return (PHASES.index(obj.get("hook", "Sync")), obj.get("wave", 0), kind_rank, obj["name"])

objects = [
    {"kind": "Deployment", "name": "linkly"},
    {"kind": "HTTPRoute", "name": "linkly", "wave": 1},
    {"kind": "Service", "name": "linkly"},
    {"kind": "ConfigMap", "name": "linkly-config", "wave": -1},
    {"kind": "Secret", "name": "linkly-db", "wave": -1},
    {"kind": "Job", "name": "linkly-migrate", "hook": "PreSync"},
    {"kind": "Job", "name": "linkly-smoke-test", "hook": "PostSync"},
    {"kind": "StatefulSet", "name": "linkly-redis", "wave": -1},
]

current = None
for obj in sorted(objects, key=sort_key):
    group = (obj.get("hook", "Sync"), obj.get("wave", 0))
    if group != current:
        if current is not None:
            print("    ... wait until healthy")
        current = group
        print(f"phase {group[0]}, wave {group[1]}:")
    print(f"    apply {obj['kind']}/{obj['name']}")
print("    ... wait until healthy")
phase PreSync, wave 0:
    apply Job/linkly-migrate
    ... wait until healthy
phase Sync, wave -1:
    apply Secret/linkly-db
    apply ConfigMap/linkly-config
    apply StatefulSet/linkly-redis
    ... wait until healthy
phase Sync, wave 0:
    apply Service/linkly
    apply Deployment/linkly
    ... wait until healthy
phase Sync, wave 1:
    apply HTTPRoute/linkly
    ... wait until healthy
phase PostSync, wave 0:
    apply Job/linkly-smoke-test
    ... wait until healthy

Redis (a StatefulSet in wave -1) must be healthy before linkly starts in wave 0, and the HTTPRoute only sends traffic once the Deployment is healthy. One consequence: an unhealthy object blocks every later wave. If Redis never becomes ready, linkly is never applied and the app stays Progressing until someone looks.

Annotate and check the order offline

The annotations live in your chart or overlay, so you can list the order a sync would use from the rendered output. This session adds them with a Kustomize patch (no chart change needed) and sorts the render by wave with yq and jq:

bash · try it yourself
mkdir -p app && cd app
cat > resources.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata: {name: linkly-config}
data: {LOG_LEVEL: info}
---
apiVersion: batch/v1
kind: Job
metadata: {name: linkly-migrate}
spec:
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers: [{name: migrate, image: ghcr.io/acme/linkly:1.4.0, args: [migrate, up]}]
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: linkly}
spec:
  selector: {matchLabels: {app: linkly}}
  template:
    metadata: {labels: {app: linkly}}
    spec:
      containers: [{name: linkly, image: ghcr.io/acme/linkly:1.4.0}]
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: linkly}
spec:
  parentRefs: [{name: public, namespace: gateway-system}]
  rules: [{backendRefs: [{name: linkly, port: 80}]}]
EOF
cat > kustomization.yaml <<'EOF'
resources: [resources.yaml]
patches:
  - target: {kind: Job, name: linkly-migrate}
    patch: |-
      - op: add
        path: /metadata/annotations
        value:
          argocd.argoproj.io/hook: PreSync
          argocd.argoproj.io/hook-delete-policy: BeforeHookCreation,HookSucceeded
  - target: {kind: ConfigMap}
    patch: |-
      - {op: add, path: /metadata/annotations, value: {argocd.argoproj.io/sync-wave: "-1"}}
  - target: {kind: HTTPRoute}
    patch: |-
      - {op: add, path: /metadata/annotations, value: {argocd.argoproj.io/sync-wave: "1"}}
EOF
kustomize build . > rendered.yaml
kubeconform -strict -summary rendered.yaml
yq -o json rendered.yaml | jq -rs '
  def ann(k; d): .metadata.annotations[k] // d;
  sort_by(ann("argocd.argoproj.io/sync-wave"; "0") | tonumber)[]
  | "\(ann("argocd.argoproj.io/hook"; "Sync")) wave \(ann("argocd.argoproj.io/sync-wave"; "0")): \(.kind)/\(.metadata.name)"'
Summary: 4 resources found in 1 file - Valid: 4, Invalid: 0, Errors: 0, Skipped: 0
Sync wave -1: ConfigMap/linkly-config
Sync wave 0: Deployment/linkly
PreSync wave 0: Job/linkly-migrate
Sync wave 1: HTTPRoute/linkly

The listing sorts by wave only; Argo CD additionally runs the PreSync Job before all waves of the Sync phase, as the model showed.

Migrations as PreSync hooks: the fine print

  • A PreSync migration runs before the new Pods exist, so the old version runs against the new schema for a while. Write backward-compatible migrations (expand, migrate, contract), as you would for any rolling update.
  • A failing PreSync Job stops the sync: nothing else is applied, the app shows the failed hook, and the old version keeps serving. That is the behaviour you want.
  • BeforeHookCreation (the default) leaves the last finished Job in the cluster for its logs; adding HookSucceeded removes it after success.
  • Under Flux there are no hooks: helm-controller runs the chart's Helm hooks, and kustomize-controller orders work with dependsOn between Kustomizations (The Kustomize Controller).

Test yourself

Objects are in waves -1, 0 and 1. A StatefulSet in wave -1 never becomes ready. What happens to wave 0?

  1. It is applied anyway after a timeout
  2. It is never applied: each wave waits for the previous one to be healthy
  3. Argo CD skips wave -1
  4. Wave 0 and 1 are applied together

Which hook is right for a database migration that must finish before the new version is applied?

  1. PostSync
  2. SyncFail
  3. PreSync
  4. Skip

A Helm chart uses helm.sh/hook: post-install,post-upgrade for a smoke-test Job. How does Argo CD treat it?

  1. Ignores it
  2. As a PostSync hook
  3. As a PreSync hook
  4. As a normal resource in wave 0