Finalizers are a special metadata primitive in k8s which blocks the deletion of an Object until certain conditions are met. The finalizers field accepts an array of special keys which indicate to the controller1 responsible for the Object what cleanup actions should be taken against Objects before completing the deletion process.

  1. When an Object is marked for deletion, the API server adds the metadata.deletionTimestamp field with the time the removal was requested, puts the Object into a “Terminating” state, starts blocking the deletion of the Object’s entry in etcd, and returns 202 Accepted.
  2. Then, the relevant controller detects the deletionTimestamp field and starts working on the actions indicated by the finalizers field on the Object.
  3. When an action is completed, the controller removes the corresponding key from the field.
  4. If the field is empty, the Object is deleted from the etcd registry, forever.

Warning

In some cases, finalizers on dependents can block the deletion of an owner Object (see Owners and Dependents in k8s). In such cases it’s important to check all owner references and all finalizer fields. This behaviour, however, depends on the garbage collection policy in use (see Garbage Collection in k8s).

Important

Finalizers aren’t only for cleaning up owned resources. They’re also used for protection: k8s automatically adds the kubernetes.io/pv-protection finalizer to prevent PVs from being deleted while a workload uses them. Only when the workload stops using the PV, the deletion will be completed.

Sources

Footnotes

  1. See k8s controllers.