Kubernetes Architecture

Kubernetes Architecture in DevOps Tools: --- A large stockroom behind a busy shop does not run on one-off orders scribbled by whoever notices an empty shelf.


The Analogy: The Stockroom Run on Par Levels

A large stockroom behind a busy shop does not run on one-off orders scribbled by whoever notices an empty shelf. It runs on par levels: a written plan states how many of each item belong on the shelf -- twelve of this, three of that -- and a stock controller walks the aisles continuously, comparing what the plan says should be there against what is actually there, and issuing exactly the requisitions needed to close the gap. The plan is the single source of truth, and the controller's entire job is to make the shelves match it, over and over, forever.

The work is divided among a few fixed roles. The plan lives in a ledger at the requisitions desk, the one place any change is ever written down, so there is always a single authoritative copy of what should exist. A separate receiving clerk decides, when new stock arrives, which aisle and shelf actually has room for it. And the stock controller runs its loop no matter who changed what: it does not need to be told that a customer just bought three units, it simply looks at the shelf, sees the shortfall, and reorders. Every request flows through the desk, placement is the receiving clerk's decision, and the ledger is the truth everyone else is measured against.

What makes this powerful is that it is declarative, not imperative. The manager never says "order five units today". The manager edits the par level -- "keep twelve" -- and walks away. Whether keeping twelve means ordering five this morning and none this afternoon is the controller's problem, recomputed fresh on every pass from the difference between the plan and the shelf. You state the end you want and the system works out the steps to get there and to stay there. This is the whole idea of the architecture in this lesson: you describe a desired state, and a control loop drives reality toward it.

The one discipline that makes the whole scheme work is that the controller must count the shelf on every pass and never trust its memory of what it last ordered. Picture a lazy controller who keeps a private tally instead -- "I have already stocked twelve, so I am finished" -- and stops looking at the shelf. A customer buys one; the shelf now holds eleven; but the tally still reads twelve, so the controller reorders nothing and the shortage stands indefinitely. The plan and the shelf drift apart silently, because the controller reconciled against its own memory rather than against reality. That is precisely the difference between the two controllers at the end of this lesson: the broken one trusts a remembered count and never notices a unit has vanished, while the correct one re-counts the shelf every loop and closes the gap.


Syntax or Core Structure

In Kubernetes you do not launch pods by hand. You submit an object describing the desired state -- here, a Deployment asking for three replicas -- and a controller works to keep exactly that many running. The manifest is the par-level plan written into the ledger:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:1.25

The controller behind that object runs one idea in a loop: read the desired count, observe how many pods actually exist, and issue the create or delete actions that close the gap. Model that single reconcile step starting from an empty cluster:

def reconcile(desired, observed):
    running = sorted(observed)
    actions = []
    i = len(running)
    while len(running) < desired:
        i += 1
        running.append('pod-%d' % i)
        actions.append('create pod-%d' % i)
    while len(running) > desired:
        victim = running.pop()
        actions.append('delete %s' % victim)
    return running, actions

state, acts = reconcile(3, [])
for a in acts:
    print(a)
print('running=%d desired=3' % len(state))

Output:

create pod-1
create pod-2
create pod-3
running=3 desired=3

From zero observed pods and a desired count of three, the loop emits three creates and stops. Had it observed five, it would have emitted two deletes instead. The manifest never lists the individual actions; it states only the target, and the same loop computes whatever create or delete steps reality currently requires -- exactly the manager who writes "keep twelve" and leaves the arithmetic to the controller.


Technical Depth: The Parts and the Placement Decision

Who does what in the cluster

Kubernetes splits into a control plane that decides and a set of worker nodes that run the containers. Each component maps onto one of the stockroom roles, and knowing which is which explains where any given failure shows up.

ComponentPlaneRole
API servercontrolthe requisitions desk: the one door for every change
etcdcontrolthe ledger: the authoritative store of desired and observed state
schedulercontrolthe receiving clerk: picks which node a new pod lands on
controller-managercontrolthe stock controller: runs the reconcile loops
kubeletnodethe shelf stocker: makes its node match what was assigned
kube-proxynodewiring: programs the network routes to pods on its node

The division matters because it localizes blame. A pod stuck Pending is a scheduler story -- nothing could place it. A pod that never becomes Running after placement is a kubelet story on its node. A change that did not take effect at all is an API-server or etcd story, upstream of everyone.

The scheduler places by capacity, and can run out

When the scheduler picks a node it is solving a bin-packing problem: each node has finite free CPU and memory, each pod requests some, and a pod that fits nowhere stays Pending rather than being forced on. Model a greedy placement where demand exceeds capacity:

NODES = {'node-a': 4, 'node-b': 2}          # free CPU units per node
PODS = [('web-1', 2), ('web-2', 2), ('web-3', 2), ('web-4', 2)]

def schedule(nodes, pods):
    free = dict(nodes)
    placement = {}
    for name, req in pods:
        placed = None
        for n in sorted(free):
            if free[n] >= req:
                free[n] -= req
                placed = n
                break
        placement[name] = placed if placed else 'Pending'
    return placement, free

place, free = schedule(NODES, PODS)
for name, req in PODS:
    print('%-6s -> %s' % (name, place[name]))
print('free: ' + ', '.join('%s=%d' % (n, free[n]) for n in sorted(free)))

Output:

web-1  -> node-a
web-2  -> node-a
web-3  -> node-b
web-4  -> Pending

Two pods fill node-a's four units, one fills node-b's two, and web-4 has nowhere to go -- total demand is eight units against six of capacity, so exactly one pod is left Pending. This is not an error the scheduler can retry away; Pending is the honest report that the cluster is out of room, and it stays that way until a node frees capacity or you add one. A reconcile loop wanting four replicas will keep four desired and three running, forever short by one, until the physical constraint changes.


Real World Example: Why the Cluster Heals Itself

Self-healing -- a crashed pod being replaced without anyone intervening -- is the property that sells Kubernetes, and it is a direct consequence of how the reconcile loop is written. There are two ways to write such a loop, and only one of them heals. An edge-triggered loop reacts to events and tracks what it believes it has done; a level-triggered loop ignores its own history and re-observes actual state every pass. Model both against a pod that crashes between loops:

DESIRED = 3

def edge_reconciler():
    created = 0; log = []
    if created < DESIRED:
        n = DESIRED - created; created += n
        log.append('loop1: created %d, believes running=%d' % (n, created))
    actual = created - 1        # a pod crashes out-of-band; the counter is unaware
    log.append('a pod crashed: actual now %d, counter still %d' % (actual, created))
    if created < DESIRED:
        log.append('loop2: counter %d < desired, would create' % created)
    else:
        log.append('loop2: counter says %d == desired, nothing to do' % created)
    log.append('edge result: actual=%d desired=%d healed=%s' % (actual, DESIRED, actual == DESIRED))
    return log

def level_reconciler():
    log = []; actual = 0
    gap = DESIRED - actual; actual += gap
    log.append('loop1: observed 0, created %d, actual=%d' % (gap, actual))
    actual -= 1                 # the same crash
    log.append('a pod crashed: actual now %d' % actual)
    observed = actual; gap = DESIRED - actual; actual += gap
    log.append('loop2: observed %d, created %d, actual=%d' % (observed, gap, actual))
    log.append('level result: actual=%d desired=%d healed=%s' % (actual, DESIRED, actual == DESIRED))
    return log

for line in edge_reconciler():
    print(line)
print('====')
for line in level_reconciler():
    print(line)

Output:

loop1: created 3, believes running=3
a pod crashed: actual now 2, counter still 3
loop2: counter says 3 == desired, nothing to do
edge result: actual=2 desired=3 healed=False
====
loop1: observed 0, created 3, actual=3
a pod crashed: actual now 2
loop2: observed 2, created 1, actual=3
level result: actual=3 desired=3 healed=True

Both loops create three pods on the first pass. Then a pod crashes. The edge reconciler's second loop consults its own counter, which still reads three, concludes nothing needs doing, and leaves the cluster permanently one short -- healed=False. The level reconciler's second loop ignores what it did last time, observes that only two pods are actually running, computes a gap of one, and creates the replacement -- healed=True. The difference is entirely in what "loop2" trusts: a remembered count, or the observed shelf. Kubernetes controllers are level-triggered by design, which is why killing a pod is answered by a new one without any event wiring to detect the death.

The level-triggered model is robust but not magic, and its assumptions are worth naming. It is only ever as correct as its observation: if the kubelet reports a pod Running that is in fact wedged, the loop believes the gap is closed and heals nothing, because it reconciles against the reported state, not the true one. It assumes its actions are idempotent and take effect before the next observation -- and the code shown quietly cheats on exactly that point, incrementing actual the instant it "creates", when real pod creation is asynchronous and a fast second loop would observe the not-yet-Running pods, compute too large a gap, and over-create. And the deeper design limit is that reconciliation targets a snapshot of desired state and cannot express ordering: it can make the counts match, but it has no notion of "roll these out gradually" or "this must start before that". That gap between "make the number right" and "change safely over time" is exactly what the Deployment controller in the next lesson exists to fill.


Common Mistakes

  1. Tracking state in the controller instead of observing it. An edge-triggered loop that trusts a remembered count never notices an out-of-band crash and leaves the cluster permanently short. Re-observe actual state every pass.
  1. Treating a pod as durable. Pods are cattle, not pets: they are created and destroyed by controllers constantly. Anything that assumes a specific pod will persist, or relies on its identity or IP, breaks on the first reschedule.
  1. Blaming the wrong component for a stuck pod. A Pending pod is a scheduling or capacity problem; a pod that placed but never runs is a kubelet or image problem. Conflating the two sends you debugging the wrong plane.
  1. Expecting the scheduler to overcommit past capacity. If nothing fits, the pod stays Pending; the scheduler does not force it onto a full node. Chronic Pending means add nodes or lower requests, not retry harder.
  1. Writing to etcd or nodes directly. Every change must go through the API server, which validates and records it. Sidestepping it to poke etcd or a node leaves the ledger and reality inconsistent.
  1. Confusing desired state with current state. replicas: 3 is a request, not a fact. The cluster may currently have two while it converges; reading the spec and assuming it describes reality is a category error.
  1. Omitting resource requests. Without requests, the scheduler cannot bin-pack sensibly and may pack a node until it thrashes. Requests are how a pod tells the receiving clerk how much shelf it needs.
  1. Assuming reconciliation implies safe rollout. The core loop makes counts match; it says nothing about doing so gradually or in order. Believing a bare controller gives you zero-downtime rollouts leads to surprises the Deployment controller is meant to prevent.
  1. Thinking a healthy count means healthy pods. The loop reconciles against reported status, so pods reported Running but actually wedged satisfy it. Liveness and readiness probes exist precisely so the reported state reflects the true one.

Best Practices

  • Write every controller to re-observe actual state each loop and drive toward desired state, never to act on a remembered log of what it believes it already did.
  • Treat pods as disposable and put identity, storage, and addressing in the objects built for it, so a rescheduled pod costs nothing.
  • Route all changes through the API server so etcd stays the single authoritative ledger and validation always runs.
  • Set resource requests and limits on every container so the scheduler can place pods correctly and one workload cannot starve a node.
  • Read status separately from spec: compare .status against .spec to know whether the cluster has actually converged rather than assuming the spec is reality.
  • Give pods liveness and readiness probes so reported state matches true state and the reconcile loop heals genuinely broken pods, not just absent ones.
  • Watch for chronic Pending as a capacity signal and scale nodes or tune requests, rather than treating it as a transient error.
  • Lean on higher-level controllers such as Deployments for anything involving ordering or gradual change, since the bare reconcile loop only makes counts match.

Practice Exercises

  1. Extend the reconcile function to start from five observed pods with a desired count of three, and confirm it emits exactly two deletes and no creates.
  1. Add a third node with three free units to the scheduler and re-run the four-pod workload. Show that web-4 now places and compute the free capacity left on every node.
  1. Modify the level reconciler so pod creation is asynchronous: a created pod is only observable on the loop after it was created. Trace two loops and show how the naive version over-creates before settling.
  1. Model a wedged pod that the kubelet reports as Running but that serves no traffic. Show that a count-only reconcile loop reports healed=True while a readiness-aware one does not, and explain which state each trusts.