Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Kubernetes,
and the desired state it chases.
Kubernetes looks like a pile of YAML and jargon, but there's one idea underneath everything: you declare the state you want, and a control loop relentlessly makes reality match it. Once that clicks, pods, deployments, services and self-healing all fall out of it.
The orchestration problem
Containers solved packaging: bundle an app with its dependencies so it runs the same everywhere. Great — for one container on one machine. But real systems run hundreds of containers across many machines, and that raises a swarm of hard questions: which machine does each container run on? What happens when one crashes, or a whole machine dies? How do containers find and talk to each other when they're constantly created and destroyed? How do you roll out a new version without downtime, or scale up under load?
Doing all that by hand doesn't work. Kubernetes is a container orchestrator: it automates placement, healing, networking, rollouts, and scaling across a cluster of machines. It turns "a fleet of containers on a fleet of servers" from a manual nightmare into something you declare and it manages.
Pods — the smallest unit
You might expect Kubernetes to schedule containers directly. Instead the smallest unit is a pod: one (or a few tightly-coupled) containers that share a network address and storage and are always placed together on the same node. Most pods hold a single app container; a second "sidecar" container (a log shipper, a proxy) is added when it must live right next to the main one.
The crucial property: pods are ephemeral. They can be created, killed, and rescheduled at any moment — a pod has no stable identity or IP you should rely on. So you don't create pods by hand and babysit them; you declare a higher-level object that owns pods and replaces them as needed. That's the next piece.
Deployments & ReplicaSets
A Deployment is how you actually run an app. You declare: "run N replicas of this container image, with these resources." Under the hood a ReplicaSet ensures exactly N identical pods exist — if one dies, it makes another; if you change N, it adds or removes pods. You never touch individual pods; you edit the Deployment's desired count and image.
Deployments also give you rolling updates: change the image and Kubernetes gradually replaces old pods with new ones, keeping the app available throughout, and can roll back if the new version misbehaves. This is the everyday interface: declare what you want running, and let the Deployment keep it that way.
You manage a Deployment → it manages a ReplicaSet → which manages Pods → which run containers. Each layer exists so failures and changes are handled automatically at the level below.
Services & networking
Pods are ephemeral with changing IPs, so how does anything reliably reach them? A Service gives a stable virtual address and DNS name that fronts a dynamic set of pods (selected by label). Traffic to the Service is load-balanced across the healthy pods behind it, and as pods come and go the Service tracks them automatically. Your other services just call payments and never worry about which pods exist right now.
This is service discovery and load balancing built in: the Service is the stable front door over an ever-changing fleet. Types range from internal-only (ClusterIP) to externally exposed (LoadBalancer), and an Ingress adds HTTP routing on top. The pattern mirrors classic load balancing and service discovery — Kubernetes just makes it declarative.
The core idea: desired state & the control loop
Everything above is a special case of one mechanism. This is the whole of Kubernetes.
Kubernetes is declarative: you don't issue commands ("start a pod on node 3"), you declare desired state ("I want 4 replicas of this running") and store it in the cluster. Then controllers run a continuous reconciliation loop: observe the actual state, compare it to the desired state, and take action to close any gap — forever.
This is why Kubernetes self-heals: a pod crashes, actual drops below desired, the controller notices the mismatch and creates a replacement — no human, no alert-driven fix, just the loop converging. Scaling, rollouts, and recovery are all the same loop chasing whatever state you declared.
The scheduler
When a new pod needs to run, the scheduler decides which node it lands on. It filters nodes that can't fit the pod (not enough CPU/memory, missing constraints) and scores the rest to pick a good home, balancing the cluster. You can influence it with resource requests/limits (how much CPU/memory a pod needs), node affinity (prefer/require certain nodes), and taints/tolerations (keep pods off, or allow onto, special nodes).
Getting resource requests right matters: request too little and pods get packed and starved; too much and you waste the cluster. The scheduler is the piece that turns "run this pod" into "run it here," and it's how Kubernetes uses a fleet of machines efficiently.
Under the hood, scheduling is bin-packing and autoscaling is one formula. A pod fits a node only if its request fits the free space; the Horizontal Pod Autoscaler resizes replicas by the ratio of observed load to target:
Two 4-CPU nodes can't place a 5th pod that needs 4 CPU when only fragments are free — it stays Pending. And 3 replicas at 90% CPU against a 50% target scale to 6. The runnable version below packs a cluster and runs the HPA.
Config, health & autoscaling
A few more pieces complete the picture. ConfigMaps and Secrets inject configuration and credentials into pods so images stay generic and environment-specific values live outside them. Health probes let Kubernetes know a container's real state: a liveness probe detects a hung container and restarts it; a readiness probe detects one that isn't ready to serve yet and holds traffic back until it is (crucial during startup and rollouts).
And autoscaling closes the loop on load: the Horizontal Pod Autoscaler (HPA) watches metrics like CPU and adds or removes replicas to match demand, while cluster autoscaling can add or remove nodes. Combined with self-healing, you get a system that repairs and resizes itself — the payoff for describing everything as desired state.
Liveness probe
- "Is it alive?"
- Fails → restart the container
- Catches hangs/deadlocks
Readiness probe
- "Is it ready to serve?"
- Fails → remove from Service (no traffic)
- Protects during startup & rollouts
Do you need Kubernetes?
Kubernetes is powerful, and it's complex — a real operational surface with its own failure modes, upgrades, and learning curve. It earns that cost when you run many services across many machines and genuinely need automated scaling, self-healing, rolling deployments, and service discovery working together. At that scale, doing it yourself is worse.
But for a single app or a handful of services, Kubernetes is often over-engineering. A managed platform (PaaS), serverless functions, or simple container hosting will ship you faster with far less to operate, and you can adopt Kubernetes later if scale demands it. The honest question isn't "is Kubernetes good?" (it is) but "does my system have the scale and complexity that justify its complexity?"
Pack a cluster and run the autoscaler
Kubernetes scheduling is bin-packing: each pod declares a CPU request and the scheduler first-fits it onto a node with room. This packs five pods onto two 4-CPU nodes and shows the two that fit nowhere left Pending — the classic capacity-fragmentation trap. Then it runs the Horizontal Pod Autoscaler's one formula, scaling 3 replicas up to 6 at 90% CPU and down to 2 at 20% against a 50% target. Change the pods, node sizes, or metrics.
Worked example: a rolling update, step by step
A Deployment runs 4 replicas of payments:v1. You change the image to v2. With the default strategy, maxSurge is 25% rounded up (1 pod) and maxUnavailable is 25% rounded down (1 pod). So the controller may run at most 4 + 1 = 5 pods, and must keep at least 4 − 1 = 3 ready at every step.
| Step | What the controller does | v1 pods (ready) | v2 pods (ready) | Total / ready |
|---|---|---|---|---|
| 0 | Before the change | 4 (4) | 0 | 4 / 4 |
| 1 | Scale v1 down by 1 (ready may drop to 3); create 2 v2 pods | 3 (3) | 2 (0) | 5 / 3 |
| 2 | Both v2 pods pass readiness, so 5 are ready | 3 (3) | 2 (2) | 5 / 5 |
| 3 | Remove 2 v1 pods, which still leaves 3 ready | 1 (1) | 2 (2) | 3 / 3 |
| 4 | Create 2 more v2 pods, up to the limit of 5 | 1 (1) | 4 (2) | 5 / 3 |
| 5 | They pass readiness; remove the last v1 pod | 0 | 4 (4) | 4 / 4 |
The readiness probe is what moves the rollout forward. If v2 never becomes ready, it stops at step 1: three v1 pods keep serving, and after progressDeadlineSeconds (600 s by default) the Deployment is marked as failed, and kubectl rollout undo returns to v1. Step 1 also needs room. The surge pod has to fit on a node. On the page’s two full 4-CPU nodes it stays Pending, and the rollout waits for capacity. Setting maxSurge to 0 and maxUnavailable to 1 swaps pods one at a time without needing extra room, at the cost of running one pod short throughout.
Cost and trade-offs: the knobs behind speed and spend
Here Time is the effect on speed or availability. Space is the effect on cluster capacity, and so on spend.
| Case | Time | Space | Why |
|---|---|---|---|
| CPU and memory requests | Set too low, pods share a busy node and slow each other down | Set too high, nodes look full while sitting idle | The scheduler packs by requests, not by real usage, so requests are your bill. |
| Limits | A CPU limit throttles the container; it is never killed for CPU | Going over a memory limit gets the container OOM-killed and restarted | CPU can be squeezed and memory cannot. Size memory limits for the peak. |
| maxSurge / maxUnavailable | More surge means faster rollouts | Surge pods need spare room while they run | A higher maxUnavailable is faster and needs no room, but runs with less serving capacity. |
| Replica count | More replicas survive a node loss without dropping capacity | Each replica reserves its requests all the time | Spread replicas across nodes, or one node failure takes all of them. |
| HPA | It reacts after the metric rises, so the burst arrives first | Pays for replicas only under load | CPU utilisation is measured as a percentage of the request, so no request means no CPU autoscaling. |
| Cluster autoscaler | A new node takes as long as a machine takes to boot and join | Removes empty nodes when load falls | It acts on Pending pods. Fragmented nodes can block scale-down. |
| Liveness probe timing | Too tight, it kills slow starters in a restart loop | No effect on capacity | Add a startup probe so liveness checks begin only after the app is up. |
| Service type | ClusterIP is internal; LoadBalancer adds a cloud load balancer | One cloud load balancer per LoadBalancer Service | An Ingress puts many HTTP services behind one load balancer. |
Most rows are the same trade in different places: reserve capacity and move fast, or run lean and wait. Requests are the one to get right first. Every other row (scheduling, autoscaling, surge room, spend) is calculated from them.
Common mistakes
- No resource requests
A pod with no requests and no limits gets the BestEffort class. It is the first to go when a node runs short of memory. The scheduler also thinks it uses nothing, and the HPA cannot compute its CPU percentage. Set requests on every container.
- A liveness probe that checks the database
If liveness fails when a dependency is down, a database blip restarts every pod at once. The restarts fix nothing, because the database is still down. Liveness should ask only “is this process stuck?”. Put dependency checks in readiness, which removes traffic without restarting.
- No readiness probe
Without one, a pod counts as ready as soon as its container starts, so the Service sends traffic before the app can serve. During a rollout, step 3 above removes old pods while the new ones are still failing requests.
- Deploying the <code>:latest</code> tag
A Deployment rolls out only when the pod template changes. Pushing a new
:latestchanges nothing in the template, so nothing happens, and pods restarted later pull whichever image is newest. Use a unique tag or a digest per release, so a rollout and a rollback both mean a known image. - Treating Secrets as encrypted
A Secret’s values are base64-encoded, which anyone can decode. Unless encryption at rest is configured, they sit readable in etcd, and anyone allowed to read Secrets in the namespace can see them. Restrict access with RBAC and turn on encryption at rest, or use an external secret store.
Where this shows up in production and interviews
- Managed clusters
EKS, GKE and AKS run the control plane (API server, etcd, scheduler, controllers) for you. You still own the requests, probes, rollouts and node pools above. Those are what break in production.
- Operators
A custom resource plus a controller lets you declare “a 3-node Postgres cluster”. The operator then runs the same observe, compare, act loop as section 05, for failover, backups and upgrades.
- GitOps
Tools such as Argo CD and Flux treat a git repository as the desired state and reconcile the cluster towards it. It is the control loop one level up: change what is in git, and the cluster follows.
- The interview version
“A node dies: what happens?” Walk through the loop: the node goes NotReady, its pods are evicted after their toleration (300 s by default), the ReplicaSet sees too few pods and creates more, and the scheduler places them where requests fit. Then mention a PodDisruptionBudget for planned drains.
Check yourself
A Deployment has 10 replicas and the default rollout settings. What is the most pods it can run, and the fewest ready, during an update?
maxSurge is 25% of 10 = 2.5, rounded up to 3, so at most 13 pods. maxUnavailable is 2.5 rounded down to 2, so at least 8 ready. The rounding favours availability: surge rounds up, unavailable rounds down.
4 replicas run at 80% CPU against a 60% HPA target. How many replicas does the HPA ask for?
ceil(4 × 80 / 60) = ceil(5.33) = 6. The percentage is relative to each pod’s CPU request, so if requests are wrong, the HPA scales on a wrong number.
A new image passes liveness but its readiness check always fails. What does the rollout do?
It stops after the first surge. New pods never count as ready, so the controller cannot remove more old pods without going under the minimum. The old version keeps serving, the rollout is marked failed at the progress deadline, and you roll back.
Your cluster runs at 95% of requested CPU. Why might a rollout hang even though nothing is broken?
The surge pod needs room for its request. With nodes nearly full it stays Pending, as on the page’s two 4-CPU nodes. Either the cluster autoscaler adds a node, or you set maxSurge to 0 so pods are replaced without needing extra room.
Quick answers
What is Kubernetes?
A container orchestrator: you declare desired state (replicas, image, resources) and it continuously makes reality match — scheduling containers, restarting failures, load-balancing, and autoscaling across a cluster.
What is a pod?
The smallest deployable unit: one or more tightly-coupled containers sharing a network and storage, scheduled together. Pods are ephemeral, so you manage higher-level objects (Deployments) that create and replace them.
What is the control loop?
Controllers continuously compare desired vs actual state and act to close the gap. It's why Kubernetes self-heals: if a pod dies, the mismatch triggers a replacement automatically.
When do you need it?
When you run many services across many machines needing automated scaling, healing, rollouts, and discovery. For one app or a few services, a PaaS/serverless/simple hosting is usually simpler and enough.
How Kubernetes works: declare what you want, a loop makes it real
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Agent Evaluations HandbookA self-contained handbook on evaluating AI agents — theory, interactive widgets, and practical guidance. Trajectory evals, tool-use scoring, LLM-as-judge, observability, and reliability for PMs, engineers, and founders.Read →
- The System Design Fundamentals HandbookThe load-bearing ideas behind every distributed system — the CAP theorem and consistency models, concurrency and locking, partitioning and replication, and consensus and coordination — each tied to a real worked design you can study interactively.Read →
- CAP Theorem & Consistency ModelsWhat a distributed system can promise when the network splits — CP vs AP, why "CA" is a myth, PACELC, and the full spectrum from linearizable to eventual consistency. Part of System Design Fundamentals.Read →
- Partitioning, Sharding & ReplicationHow one dataset becomes many — range vs hash partitioning, consistent hashing and virtual nodes, hot partitions, replication topologies, replication lag, and quorums. Part of System Design Fundamentals.Read →
- Consensus, Transactions & CoordinationHow nodes that can crash still agree on one truth — majority quorums, Raft and Paxos, leader election, two-phase commit vs the saga pattern, and idempotency for exactly-once effects. Part of System Design Fundamentals.Read →
- The Agent Patterns HandbookThe design patterns behind every LLM agent — the ReAct Thought–Action–Observation loop, tool/function calling, plan-and-execute, reflection, memory, multi-agent orchestration, and the failure modes (loops, hallucinated tools, recovery, human-in-the-loop) that break agents in production.Read →