Kubernetes Architecture, Operations, and Troubleshooting Questions
How Kubernetes works, how to run it, and how to debug it. Covers control-plane and node components, the scheduler and API server, cluster design, high availability and multi-cluster topologies, and platform-level operations; the workload primitives (pods, deployments, services, controllers), cluster upgrades, and designing Kubernetes as an internal platform; and the operational depth inside a cluster including pod and service networking, ingress and the CNI model, service mesh, persistent volumes and storage classes, resource requests and limits, and systematically diagnosing scheduling, networking, and storage failures. The full architecture-through-day-two-operations span of Kubernetes.
HorizontalPodAutoscaler (HPA) is not scaling a deployment even though CPU usage is above the configured target. Provide a troubleshooting plan including which metrics endpoints and API resources to check, how to validate metrics-server or custom metrics adapters, and common misconfigurations that prevent scaling.
Sample Answer
When CPU usage is genuinely above target but the Horizontal Pod Autoscaler (HPA) will not scale, the fault is almost always in the metrics plumbing between the container and the HPA controller (missing resource requests, a metrics-server or custom-metrics adapter that is not actually returning data, or a scaleTargetRef/selector mismatch) rather than in the scaling decision logic itself, which is a small, deterministic formula once it has correct inputs.
How the HPA actually decides (not scaling strategy, the mechanics)
The controller (autoscaling/v2 API, the current stable version; the earlier autoscaling/v2beta2 was removed in Kubernetes 1.26, so a cluster still authoring v2beta2 manifests is itself a currency problem worth checking for) recomputes replica count on a fixed sync period (default 15s) using:
with a tolerance band (default 10%, --horizontal-pod-autoscaler-tolerance) below which it intentionally does nothing, to avoid thrashing on noise. This tolerance and sync period explain most "it's above target but nothing happens" reports that turn out to be working as designed: a ratio of 1.05 (5% over target) is inside the default tolerance band and will not trigger a scale event.
Checklist, in order of how often each one is the actual cause
- HPA state and events, the fastest signal:
kubectl describe hpa myapp-hpa -n myapp
Look for the Conditions block and events such as:
Warning FailedGetResourceMetric hpa-controller
failed to get cpu utilization: unable to get metrics for resource cpu:
missing request for cpu
That specific event means the fix is a resource request, not anything about metrics-server health.
2. CPU utilization requires requests, always. HPA's Utilization metric type is computed as usage divided by the container's CPU request, not its limit. If a container has no resources.requests.cpu, the HPA controller cannot compute a percentage at all and reports the event above, regardless of how busy the pod actually is.
3. Metrics API is actually serving data:
kubectl top pods -n myapp
kubectl get --raw "/apis/metrics.k8s.io/v1beta1/namespaces/myapp/pods" | jq
If kubectl top returns nothing, metrics-server itself is the suspect, not the HPA:
kubectl get pods -n kube-system -l k8s-app=metrics-server
kubectl logs -n kube-system <metrics-server-pod>
- Custom or external metrics, if the HPA targets something other than CPU/memory:
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1" | jq
An empty or erroring response here means the metrics adapter (commonly the Prometheus Adapter) is not registered correctly as an APIService, or the metric name in the HPA spec does not match the name the adapter actually exposes (a very common typo-class bug: the HPA references http_requests_per_second while the adapter exposes requests_per_second).
5. scaleTargetRef correctness: confirm .spec.scaleTargetRef.kind/.name in the HPA actually matches the Deployment being scaled; a stale reference (left over from a renamed Deployment) means the HPA is quietly watching nothing.
6. Pod readiness: the HPA only counts Ready pods toward currentReplicas and current metric averaging; a pod stuck failing its readiness probe is invisible to the calculation even though it is consuming CPU.
7. minReplicas/maxReplicas bounds: confirm maxReplicas is actually above the current replica count; a forgotten low ceiling silently caps scaling with no error at all.
Worked example
Suppose myapp-hpa targets 50% average CPU utilization, is currently running 4 replicas, and kubectl top pods shows the average pod is using CPU equal to 82% of its request. Plugging into the formula:
If the HPA is healthy, kubectl describe hpa should show current / target: 82% / 50% and a scaling event moving the Deployment toward 7 replicas. If instead the describe output shows no current value at all (a blank or <unknown>), the problem is upstream of this formula entirely: metrics are not reaching the controller, so there is nothing for the formula to compute against.
Trade-offs and pitfalls
- This checklist deliberately does not touch which metric to scale on or whether reactive CPU-based scaling is the right strategy for the workload; that is a scaling-strategy design decision, separate from why a correctly-configured HPA fails to act mechanically.
- A common wrong turn is restarting metrics-server or the HPA controller as a first move; that only helps if the actual event says the adapter is unresponsive, and it resets nothing if the real cause is a missing CPU request or a
scaleTargetReftypo. - Combining HPA with a Vertical Pod Autoscaler (VPA) on the same CPU metric can fight itself: VPA changing requests up or down changes the denominator HPA's utilization percentage is computed against, producing scaling behavior that looks erratic but is actually two controllers correctly reacting to each other.
- The tolerance band means "barely above target" is not a bug; check the actual ratio before assuming the controller is broken.
Explain the differences between Deployment and StatefulSet. Provide a scenario (e.g., a database cluster) that requires StatefulSet semantics and explain which StatefulSet features (stable network IDs, ordinal indexes, persistent volumes) are necessary.
Sample Answer
Deployment and StatefulSet both manage a set of pods from one template, but a Deployment treats every pod as interchangeable, while a StatefulSet gives each pod a stable, ordinal identity and its own dedicated storage. Reach for StatefulSet only when the application itself needs to know which replica it is, not just how many replicas exist.
Direct comparison
| Deployment | StatefulSet | |
|---|---|---|
| Pod naming | random suffix, no ordering | ordinal suffix (pod-0, pod-1, ...), stable across restarts |
| Network identity | pod IP changes on recreation; normally fronted by a load-balancing Service | stable hostname per ordinal, usually via a headless Service (clusterIP: None), so pod-0.svc.namespace.svc.cluster.local always resolves to the same replica |
| Storage | usually shared, external, or none | one PersistentVolumeClaim (PVC, a request for storage) bound to a PersistentVolume (PV, the actual storage resource) per ordinal, via volumeClaimTemplates; deleting the StatefulSet does not delete these PVCs |
| Startup and scale order | no ordering guarantee | default OrderedReady policy starts and stops one ordinal at a time, lowest-to-highest on scale-up and highest-to-lowest on scale-down; a Parallel policy is available when the app does not need this ordering |
Worked example: a PostgreSQL primary-replica cluster
A database cluster with one primary and several read replicas needs exactly the guarantees a Deployment cannot give:
- Stable hostnames: replication configuration and client connection strings can target
postgres-0.postgres-svcby name, and that name always means the same replica, even across restarts. - Ordinal indexes: an init script can branch on the pod's ordinal (ordinal 0 initializes as primary, ordinals 1 and above join as replicas) and rely on ordered startup so replicas do not attempt to join before the primary exists.
- Per-ordinal persistent volumes:
volumeClaimTemplatesties each replica's data directory to its own ordinal, sopostgres-1always reattaches topostgres-1's data after a restart, never to another replica's.
Trade-offs and pitfalls
- Not everything with 'stateful' in its name needs a StatefulSet. Kafka brokers do: each broker owns local partition log segments on disk and needs a stable identity for replica assignment. Kafka Connect workers do not: a Connect worker's task state and offsets live in Kafka topics, not on local disk, so the worker pool is effectively stateless and runs fine as a plain Deployment. Confirm where the durable state actually lives before defaulting to StatefulSet.
- StatefulSet's ordered rollout is slower and more conservative than a Deployment's by design; if a stateful workload's replicas are genuinely independent (sharded, no leader election), that ordering guarantee adds rollout latency with no real benefit, and a
Parallelpod-management policy, or even a Deployment with per-shard volumes mounted individually, may fit better. - Deleting a StatefulSet leaves its PVCs behind on purpose, to protect data from an accidental delete. Teams that do not know this get surprised in both directions: unexpected data loss if they assumed cleanup was automatic, or orphaned storage cost if they never clean it up.
Design an etcd backup and restore strategy that meets RPO = 5 minutes and RTO ≤ 30 minutes for a cluster controlling 1000 nodes. Include snapshot frequency, WAL archival, offsite storage, automation, validation testing, encryption, and practical considerations for large snapshot sizes.
Sample Answer
Meet RPO = 5 minutes and RTO <= 30 minutes with two layers: a snapshot cadence tight enough to bound data loss, and a rehearsed, automated restore pipeline that removes human decision-making from the critical path. etcd (the strongly-consistent key-value store that is the single source of truth for all cluster state, including every object the API server serves) has exactly one supported backup primitive: a full point-in-time snapshot via etcdctl snapshot save. There is no supported mechanism to continuously ship etcd's internal write-ahead log (WAL, the durability journal etcd itself uses before committing to its storage engine) to an external archive and replay it to an arbitrary revision the way you would with a database that ships transaction logs (for example Postgres WAL archiving). Treating WAL files as an externally replayable artifact is a common design mistake; the design below does not rely on it.
Component design
| Concern | Approach | Why |
|---|---|---|
| Snapshot cadence | Full etcdctl snapshot save every 2 minutes | Bounds RPO to the cadence itself; 2 minutes gives headroom under the 5-minute target for scheduling jitter |
| Sub-cadence data loss | Frequent storage-level (block/volume) snapshots of the etcd data directory on a schedule between application snapshots, or a warm-standby etcd learner member | Closes the gap between snapshot ticks without inventing WAL-replay tooling that does not exist |
| Offsite durability | Upload each snapshot to object storage in a second region immediately after it completes, with server-side encryption and versioning enabled | Survives a full primary-region loss |
| Automation | A CronJob or systemd timer runs snapshot, checksum, encrypt, upload, and prune as one pipeline; the restore path is an equally scripted, idempotent runbook, not ad hoc commands | Removes operator error from the critical 30-minute window |
| Validation | Nightly automated restore into a scratch environment plus a periodic full DR game day | An untested backup is a hypothesis, not a plan |
| Encryption | TLS in transit for both the etcd peer/client traffic and the upload; server-side encryption at rest in object storage, with client-side envelope encryption via a key management service for the most sensitive clusters | Snapshots contain every Secret's ciphertext-at-rest plus the encryption-at-rest key references; treat them as highly sensitive |
| Large snapshot size (1000 nodes) | Compact and defragment before snapshotting; compress with a fast codec; chunked/multipart upload | A 1000-node cluster with dense workloads can push the etcd dataset into multiple gigabytes, and etcd's own guidance is to keep the working set well under its default 2 GiB backend quota (raisable, but performance degrades well before you would want to push it much past single-digit gigabytes) |
flowchart LR
A[etcdctl snapshot save] --> B[checksum + zstd compress]
B --> C[encrypt: KMS envelope]
C --> D[multipart upload to primary-region bucket]
D --> E[cross-region replication]
F[nightly restore job] --> G[scratch cluster]
E --> F
G --> H[consistency + smoke test]
H --> I[alert on failure]
Compaction and defragmentation (day-2 maintenance that feeds the backup design)
etcd's storage engine is an MVCC (multi-version concurrency control) store: every write creates a new revision, and old revisions accumulate until removed. Two distinct operations matter here and the basis design blurred them:
- Compaction (
etcdctl compactor--auto-compaction-retention) discards historical revisions older than a retention point. It shrinks the logical keyspace but does not shrink the on-disk file. - Defragmentation (
etcdctl defrag) reclaims that freed space at the storage-engine level. It must be run one member at a time, off-peak, because a member briefly stops serving requests while it defrags; running it cluster-wide at once risks a quorum-visible latency spike or, in the worst case, a temporary loss of quorum if it overlaps with another disruption.
Run compaction continuously (auto-compaction) and defragmentation on a rotating per-member schedule shortly before the snapshot window, so the snapshot reflects a compacted, defragmented (and therefore smaller and faster to transfer and restore) dataset.
Cross-version restore caveat
A snapshot embeds objects serialized at whatever API storage version was in effect when they were written. Kubernetes deprecates and eventually removes old API versions on its normal release cadence. If you restore a snapshot taken on an older Kubernetes minor version directly onto a control plane several minors ahead, objects stored under a since-removed API version may not deserialize correctly, and the standard upgrade path (one minor version at a time) does not apply retroactively to a restored snapshot. The safe sequence is: restore into a control plane running the same (or adjacent, supported) Kubernetes version as the snapshot's source, confirm the cluster is healthy, then upgrade forward normally. Do not treat "restore, then jump several versions" as equivalent to "upgrade, then restore."
The PV data etcd does not back up
etcd stores the PersistentVolume (PV) and PersistentVolumeClaim (PVC) objects (the binding metadata: which claim is bound to which volume, capacity, storage class), not the actual bytes sitting on the underlying disks. Restoring etcd alone rehydrates the metadata but not the data on the volumes; if the real volumes have moved on or been deleted since the snapshot was taken, the restored PVC objects can point at storage that no longer matches. A cluster running stateful workloads needs a coordinated backup (for example Velero with a volume-snapshot plugin) that captures PV data snapshots at a consistent point relative to the etcd snapshot, not just the etcd side of the picture.
Restore-time budget (illustrative, not a benchmark)
The 30-minute RTO is a budget you allocate across steps, not a single measured number (actual time depends on cloud provider, disk and network throughput, and snapshot size, so do not present it as a guarantee):
| Step | Illustrative budget |
|---|---|
| Detect failure, page, and confirm restore is the right call | a few minutes |
| Provision or reuse pre-warmed etcd member nodes | a few minutes if pre-warmed, much longer if built from scratch |
| Download and decompress the snapshot | scales with snapshot size and network throughput |
etcdctl snapshot restore and bring members up, verify quorum | a fixed, testable cost you measure in your own drills |
| Health-check the control plane and run smoke tests | a few minutes |
Pre-provisioning restore nodes (rather than building them from scratch during the incident) is usually the single biggest lever for hitting a 30-minute target, because it removes the least predictable step from the critical path.
Trade-offs and pitfalls
- Tighter snapshot cadence reduces RPO but increases I/O load on the leader and snapshot storage cost; 1-2 minutes is a reasonable floor for a 1000-node cluster without specialized tuning.
- A warm-standby etcd learner member (a non-voting member that replicates writes, available since etcd 3.4) can shrink the effective RPO further, but it adds an always-on member to operate and is not a substitute for offsite snapshots since it shares the same cluster's failure domain unless deliberately placed elsewhere.
- Skipping defragmentation to save time on the backup path makes every subsequent snapshot, upload, and restore slower; it is cheaper to pay that cost on a schedule than under incident pressure.
- The most common way this design fails in practice is not the backup half, it is an untested restore: teams that only test
snapshot saveand never rehearsesnapshot restoreunder time pressure regularly discover their real RTO is far higher than 30 minutes on the first real incident.
Explain how online PVC resizing works in Kubernetes. Describe the necessary conditions (StorageClass allowVolumeExpansion, filesystem support, kubelet/node support) and the steps you would take to resize a PVC from 100Gi to 200Gi with minimal downtime.
Sample Answer
Direct answer
Online PersistentVolumeClaim (PVC) expansion needs three things to line up: the StorageClass must set allowVolumeExpansion: true, the CSI (Container Storage Interface) driver must implement the ControllerExpandVolume and NodeExpandVolume calls, and the filesystem plus kubelet must support growing in place (resize2fs for ext4, xfs_growfs for xfs). When all three hold, resizing from 100Gi to 200Gi is a one-line patch to the PVC with no pod restart. When the node-side piece is missing, the pod needs a restart to pick up the new size, which is the only source of downtime in the whole process.
Structured elaboration
Preconditions
$ kubectl get storageclass fast-ssd -o jsonpath='{.allowVolumeExpansion}'
true
If this is empty or false, expansion is rejected at the PVC level before anything else matters. Patching allowVolumeExpansion onto an existing StorageClass is safe; it only affects future resize requests, not past provisioning.
Steps to go from 100Gi to 200Gi
$ kubectl patch pvc data-pvc -p '{"spec":{"resources":{"requests":{"storage":"200Gi"}}}}'
persistentvolumeclaim/data-pvc patched
Kubernetes then drives two calls against the CSI driver in sequence:
ControllerExpandVolume, issued by the external-resizer sidecar, grows the underlying block device (or cloud volume) and updates the PersistentVolume's recorded capacity.NodeExpandVolume, issued by the kubelet on whichever node has the volume mounted, grows the filesystem to fill the new device size.
Watch the PVC's events to see this happen:
$ kubectl describe pvc data-pvc
Events:
Type Reason Message
Normal Resizing External resizer is resizing volume
Normal FileSystemResizeSuccessful MountVolume.NodeExpandVolume succeeded for volume "pvc-..."
If the CSI driver only supports offline expansion, the event sequence instead pauses at FileSystemResizePending. The fix is to let the pod restart (respecting any PodDisruptionBudget) so the kubelet can run NodeExpandVolume against the volume once it is unmounted and remounted.
Minimizing downtime for the offline case
For a single-replica stateful workload the restart is unavoidable but brief. For a replicated one, cordon and evict one replica at a time so the others keep serving, exactly the pattern a PodDisruptionBudget protects during any voluntary disruption, resize included.
Worked example
A 100Gi PVC backed by a CSI driver that supports online expansion is patched to 200Gi. ControllerExpandVolume grows the cloud volume to 200Gi and the PersistentVolume object's capacity updates to match; NodeExpandVolume then runs resize2fs (or the xfs equivalent) against the already-mounted filesystem, and kubectl describe pvc shows FileSystemResizeSuccessful without the pod ever restarting. If the same driver only supported offline expansion, the sequence would stop at FileSystemResizePending until the pod is deleted and rescheduled, at which point the kubelet completes the resize during the new mount.
Trade-offs and pitfalls
- PVCs can only be resized upward; shrinking is not supported the same way.
- Not every CSI driver implements online (in-place) expansion. Check the specific driver's documentation rather than assuming; "supports expansion" and "supports expansion without a restart" are different claims.
- Resize during low traffic and keep a snapshot beforehand. The resize itself does not touch existing data, but any manual filesystem operation carries risk if interrupted.
You maintain a widely used CustomResourceDefinition (CRD) and must introduce a breaking schema change. Design a migration strategy across API versions, including CRD versioning, conversion webhooks, a migration controller, data migration steps, and how to coordinate clients and controllers to avoid downtime.
Sample Answer
A breaking CRD (CustomResourceDefinition, the mechanism that registers a new custom object type into the Kubernetes API) schema change is handled by running two versions side by side rather than cutting over: add the new version as served alongside the old one, put a conversion webhook between them so every client keeps working regardless of which version it speaks, run a migration controller that rewrites persisted objects onto the new shape, and only flip the storage version (and eventually drop the old one) once nothing in the fleet still depends on it. The property that makes this safe is that served and storage are independent per-version flags: a version can stay served for old clients long after it has stopped being how objects are written to etcd.
1. CRD versioning
Kubernetes CRDs are apiextensions.k8s.io/v1 (the only supported API version; v1beta1 was removed in Kubernetes 1.22, so pin your tooling to v1 if you're touching anything older). Each entry in spec.versions can independently be served (clients can request it) and storage (this is the shape actually persisted in etcd; exactly one version must have storage: true).
spec:
versions:
- name: v1
served: true
storage: true # existing shape, still the write-path today
- name: v2
served: true
storage: false # new shape, readable/writable via conversion
conversion:
strategy: Webhook
webhook:
clientConfig:
service: {name: crd-converter, namespace: platform, path: /convert}
conversionReviewVersions: ["v1"]
Use conversion.strategy: Webhook (not None) whenever the change is genuinely breaking. None only works when the two versions are structurally identical except for a rename, since it does no real transformation.
2. Conversion webhook
A small, stateless HTTPS service implementing the ConversionReview API: given an object in version A, return it in version B. It runs on every read, list, and watch that crosses versions, so it sits on the request hot path and needs its own availability (multiple replicas, readiness probes, low latency) since a webhook outage makes the CRD's non-storage versions unreadable. The detail most people miss: conversion must be lossless for fields the other version doesn't know about. If v2 adds a field that v1 has no place for, converting v2 to v1 has to stash that field somewhere recoverable (commonly an annotation) rather than silently dropping it, or a client that reads it back as v2 loses data it never touched.
3. Migration controller
The webhook converts on the fly; it does not rewrite what's stored in etcd. A separate migration controller (or the community kube-storage-version-migrator add-on, API group storagemigration.k8s.io/v1beta1, which requires a 1.30+ API server with the StorageVersionMigrator feature gate) performs the one-time job of listing every existing object and issuing a no-op update, which forces the API server to re-serialize it in whatever version is currently marked storage: true. Until that rewrite runs, old objects sit in etcd in the old format and are converted up to v2 on read; new writes go straight to v2. Run the migration rate-limited and namespace-by-namespace so a large object count doesn't overload the API server, and track per-object migration state so a partial run can resume.
4. Coordinating clients and controllers
| Phase | storage version | served versions | who can be running |
|---|---|---|---|
| A: introduce v2 | v1 | v1, v2 | old clients/controllers unaffected; new code can start targeting v2 |
| B: bulk migrate | v1 | v1, v2 | migration controller rewrites objects; both old and new controllers reconcile correctly via the webhook |
| C: flip storage | v2 | v1, v2 | all writes land as v2 natively; v1 reads still work via conversion |
| D: retire v1 | v2 | v2 only | only after telemetry shows zero v1 requests |
Multiple controller versions can run against the same objects during B and C because every read comes back in whatever version the controller asked for; the risk is two controllers racing to write the same object in different versions and stomping each other's fields, which is why a canary-then-bulk migration (not "flip everything at once") matters.
5. Rollback and safety
Take an etcd snapshot before flipping the storage version. Rollback from phase C is just flipping storage back to v1 and leaving the webhook running; rollback from D (after v1 is dropped) is much harder, which is why D should only happen once request-metrics or audit logs confirm nothing is still asking for v1.
Worked scenario
For a CRD with roughly 40 known consumers, a realistic sequencing looks like: week 0, add v2 as served (storage stays v1), start the migration controller against a single low-traffic namespace as a canary and watch its metrics; week 1, if the canary is clean, run the migration across the rest of the objects in rate-limited batches; week 2, once 100% of objects report migrated: true in their status and the conversion webhook's request counts show v1 traffic has stopped growing, flip storage to v2; week 3+, after confirming no client has requested v1 in that window, drop v1 from served and retire the webhook. This is a schedule, not a measured result, and is meant to illustrate the ordering, not a fixed timeline for every CRD.
Trade-offs and pitfalls
- The conversion webhook is a new single point of failure on the CRD's read path; under-provisioning or forgetting its own rollout strategy turns a schema migration into an availability incident.
- Flipping the storage version before validating the bulk migration is fast but risky: if the new schema has a subtle bug, everything written after the flip is in the new (possibly wrong) shape.
- For a CRD with very few consumers, all of this machinery can be overkill: a coordinated breaking change with a short deprecation window and direct communication to the small client list may be cheaper than building conversion + migration infrastructure. Reach for the full multi-version path when you can't enumerate or coordinate every consumer directly.
Unlock Full Question Bank
Get access to all Kubernetes Architecture, Operations, and Troubleshooting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.