Deep Dive into the Kubernetes Control Plane: What Happens After kubectl apply

Contents

You have typed kubectl apply -f deployment.yaml maybe ten thousand times. It prints one line, deployment.apps/web created, and a few seconds later you have pods.

Expectation vs reality of kubectl apply
Fig. 1: what you think happens vs. what actually happens

This post is about the right side. We take one Deployment and follow it through every component of the control plane: what each one reads, what it writes, and why. Every output below comes from a real cluster. Nearly every outage I have debugged (“pods stuck Pending”, “the API server is slow”, “my controller fired twice”) turns out to be one of these hops misbehaving.

The setup#

A single-node kind cluster running Kubernetes v1.34, and the most boring Deployment possible:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: default
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: nginx
        image: nginx:1.27
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 100m
            memory: 64Mi

The big picture first#

Kubernetes control plane overview
Fig. 2: every arrow goes through the API server

Two rules explain almost everything that follows:

  1. Only the API server talks to etcd. The controller-manager, the scheduler and the kubelets never talk to each other, only to the API server.
  2. Every component is a control loop. Each one watches the objects it cares about, compares desired with actual state, and writes the difference back. Nobody calls anybody; components coordinate by writing objects that others watch.

So “creating a Deployment” means: you write one object, and a chain of loops each write the next. Deployment → ReplicaSet → Pods → spec.nodeName → containers → status. Let’s walk the chain.

Hop 0: kubectl, before anything leaves your laptop#

Turn the verbosity up and kubectl shows its HTTP traffic:

kubectl apply -f deployment.yaml -v=7
kubectl apply -v=7 output
Fig. 3: kubectl apply at -v=7, every request with its headers

Stripped down:

GET  /openapi/v3                                              200 OK         6ms
GET  /openapi/v3/apis/apps/v1?hash=E6837BF0...                200 OK         0ms
GET  /apis/apps/v1/namespaces/default/deployments/web         404 Not Found  1ms
POST /apis/apps/v1/namespaces/default/deployments?fieldManager=kubectl-client-side-apply&fieldValidation=Strict
                                                              201 Created    3ms
deployment.apps/web created
  • OpenAPI v3 gives client-side apply the schema it needs for strategic-merge patches. Discovery (/api, /apis) is missing because it’s cached under ~/.kube/cache/discovery.
  • GET → 404. The object doesn’t exist, so this is a create. Later applies do a three-way merge with the last-applied-configuration annotation and send a PATCH.
  • POST with fieldValidation=Strict: typo replica: and the server returns a 400 with the exact field path.

With --server-side this collapses into a single PATCH. The server does the merge and records field ownership in metadata.managedFields, so conflicts between tools become explicit errors.

Hop 1: kube-apiserver, the only door#

Inside kube-apiserver
Fig. 4: a write request’s path through kube-apiserver

The API server is a Go HTTP handler wrapped in a chain of filters, followed by a REST handler per resource:

  • Authentication. x509 certs, bearer tokens, ServiceAccount JWTs, OIDC. Nothing matches → 401.
  • API Priority and Fairness. Requests are queued per flow so one noisy client can’t eat the server’s concurrency. Overflow → 429.
  • Authorization. Node,RBAC on most clusters. RBAC never denies, so a 403 usually means nobody allowed it.
  • Defaulting. Fields you never wrote, like maxSurge: 25% and revisionHistoryLimit: 10, appear here.
  • Admission. Mutating webhooks run one after another since each can change the object; validating webhooks and CEL policies run in parallel.
  • Storage. Encoded as protobuf, optionally encrypted, written to etcd.

Production note: a webhook with failurePolicy: Fail and one unhealthy replica can freeze every write it matches. Scope webhooks tightly.

Hop 2: etcd, the bytes on disk#

kind runs etcd as a static pod, so we can exec into it and look at the raw keys (etcdctl below is a small wrapper around kubectl -n kube-system exec etcd-cp-deepdive-control-plane -- etcdctl with the etcd client certs):

etcdctl get /registry --prefix --keys-only | grep web
etcd keys for the web Deployment
Fig. 5: one Deployment, one ReplicaSet, three Pods, and 22 Events

The value itself:

Hex dump of the Deployment value in etcd
Fig. 6: the first bytes of /registry/deployments/default/web

That k8s\x00 prefix is Kubernetes’ protobuf envelope. No JSON anywhere. With encryption at rest you’d see k8s:enc:aescbc:v1:<key>: and ciphertext instead.

etcd revisions vs resourceVersion
Fig. 7: mod_revision and resourceVersion are the same number

resourceVersion is etcd’s mod_revision: the cluster-wide revision at which the object was last written, not a per-object counter. version: 7 is your create plus six updates from the Deployment controller.

It’s also how optimistic concurrency works: an update compares against the resourceVersion you sent, and if anyone wrote in between you get 409 Conflict. No locks, only compare-and-swap, which is why every controller needs a retry-on-conflict path.

Hop 3: the watch cache, or how a write reaches everyone#

Nobody else watches etcd. The API server holds one etcd watch per resource and fans it out from memory to every client. Here’s the raw stream (trimmed to one line per event with jq) while I ran kubectl scale deploy web --replicas=5 in another terminal:

kubectl get --raw "/apis/apps/v1/namespaces/default/replicasets?watch=1&resourceVersion=734"
Raw ReplicaSet watch stream while scaling 3 to 5
Fig. 8: every write to the ReplicaSet arrives as a MODIFIED event

The Deployment controller changed the spec (rv=738), the ReplicaSet controller updated status (rv=751), and kubelets reported readiness (rv=765, 768). Spec is written by whoever wants something, status by whoever does the work.

If revision 734 had already been compacted away, the server would answer 410 Gone and the client would re-LIST. A whole fleet doing that at once is the “relist storm” you see after an upgrade.

Hop 4: kube-controller-manager, a bundle of loops#

kube-controller-manager is one binary running about forty controllers. Only one replica is active at a time, chosen through a Lease:

Leases in kube-system
Fig. 9: leader-election leases (the apiserver-* one is the API server’s identity lease)

Every controller inside it is built the same way:

Inside kube-controller-manager
Fig. 10: the informer + workqueue pattern every controller uses

A reflector LISTs once, then WATCHes, filling an in-memory indexer that listers read. Event handlers do no work: they only push a key like default/web onto a workqueue, which deduplicates and backs off on failures. A worker then reads the current object and reconciles.

The key design choice: the handler gets a key, not an event. Reconcile never asks “what changed?”, only “what should the world look like now?”. That’s level-triggered: drop an event or process one twice and the next sync fixes it. It’s also why a controller “firing twice” is normal and reconcile must be idempotent.

The Deployment controller#

syncDeployment("default/web") hashes the pod template to get 74bc6b8bf8, finds no ReplicaSet with that pod-template-hash, and creates web-74bc6b8bf8 with 3 replicas:

Deployment controller events
Fig. 11: the Deployment controller’s only action: scale a ReplicaSet

It never creates a Pod. A rollout is just this controller shifting replicas between the old and new ReplicaSet.

The ReplicaSet controller#

It sees replicas: 3 and zero pods. Its cache only learns about new pods when the watch event comes back, so a sync in that window would create 3 more. To avoid that it records expectations (“I expect 3 creations”) and skips syncs until the informer has seen them all.

ReplicaSet controller events
Fig. 12: three pod creations, one per missing replica

The pods now exist with an empty spec.nodeName, and nothing will run them until someone fills it in.

Hop 5: kube-scheduler, one field#

The scheduler is another controller with a narrow job: watch pods with no spec.nodeName and set it.

Inside kube-scheduler
Fig. 13: the scheduling framework, from queue to bind

New pods go into activeQ, ordered by priority. The scheduling cycle then runs one pod at a time:

  • Filter. Can this pod run here? NodeResourcesFit, NodeAffinity, TaintToleration, …
  • Score. Plugins rate each feasible node; highest total wins.
  • Reserve. The pod is assumed onto the node in the scheduler’s cache, so the next pod sees those resources as used.
  • Bind. A POST to pods/<name>/binding, and the API server sets spec.nodeName.

Pods that fit nowhere wait in an unschedulable queue until a cluster event might help.

What actually happened on my cluster#

I applied the Deployment seconds after creating the cluster:

Scheduler events
Fig. 14: FailedScheduling on a not-ready node, then Scheduled once the taint is gone

The node still had a not-ready taint while kind’s CNI started. When the taint was removed, that Node update woke the pods up and they were bound. Nothing polled.

Hop 6: the kubelet#

Inside the kubelet
Fig. 15: from spec.nodeName to a running container

Each kubelet watches pods with spec.nodeName=<its own name>. That’s the whole contract. For each pod, a pod worker runs syncPod:

  1. Admit the pod again, since the scheduler’s view could be stale. This is where OutOfcpu comes from.
  2. Create the pod’s cgroup and mount volumes.
  3. CRI RunPodSandbox to containerd: start the pause container; the CNI plugin assigns the pod IP.
  4. PullImage, then CreateContainer / StartContainer.
Kubelet image pull events
Fig. 16: the first pull does the work; the other two mostly wait for it

Once the container runs, the kubelet patches the pod’s status with its IP and Ready condition.

Closing the loop#

That status patch is one more watch event, and the chain runs in reverse: the ReplicaSet updates readyReplicas, and the Deployment becomes Available.

Dozens of events and several etcd writes to the Deployment alone, all from one kubectl apply. So the next time it prints created and you go get coffee, remember the half-dozen control loops and hundreds of watch events working while you wait.

Comments

Sign in with GitHub to react or leave a comment.

← All posts