Stage 3, Part 2 of 10, Control Plane Internals

Text

PART 2: ADVANCED CONCEPTS

6. Admission Webhooks

Mutating vs Validating

AspectMutatingValidating
PurposeModify the objectAllow or deny
WhenFirst phaseSecond phase
Can modify?✅ Yes❌ No
Can deny?✅ Yes✅ Yes

The Ordering

  1. Mutating webhooks run first.
  2. Validating admission policies run.
  3. Validating webhooks run last.

Critical: Mutations by mutating webhooks cause all previously called webhooks to be called again.

Failure Policy

PolicyBehavior
FailReject the request if the webhook is unreachable
IgnoreAllow the request if the webhook is unreachable

The default is Fail (unless overridden).

The recovery pattern: If a webhook is blocking cluster recovery, temporarily patch to Ignore:

bash
kubectl patch validatingwebhookconfiguration my-webhook --type='json' \
  -p='[{"op":"replace","path":"/webhooks/0/failurePolicy","value":"Ignore"}]'

⚠️ Warning: This disables enforcement. Use only during confirmed outages.

Webhook Timeout

Admission webhooks created using admissionregistration.k8s.io/v1 default to 30-second timeout.

The Four Extension Points

ControllerPurpose
MutatingAdmissionWebhookExternal mutating webhooks
MutatingAdmissionPolicyDeclarative in-API mutations
ValidatingAdmissionWebhookExternal validating webhooks
ValidatingAdmissionPolicyDeclarative in-API validation

ValidatingAdmissionPolicy provides a way to embed declarative validation code within the API without relying on external HTTP callouts.


7. API Priority and Fairness (APF)

APF controls API server behavior under overload. It's stable since Kubernetes v1.29.

The Problem APF Solves

The legacy controls (--max-requests-inflight, --max-mutating-requests-inflight) limit outstanding work but don't ensure important requests get through.

How APF Works

ConceptPurpose
FlowSchemaCategorize incoming requests
PriorityLevelConfigurationAssign priority levels
QueueBuffer requests during bursts
Fair QueuingPrevent starvation

APF classifies and isolates requests in a fine-grained way. It introduces limited queuing so no requests are rejected during brief bursts. Requests are dispatched using fair queuing so a poorly-behaved controller doesn't starve others.

The Priority Levels

APF has built-in priority levels:

LevelPurpose
systemControl plane components
workload-highCritical workloads
workload-lowStandard workloads
global-defaultEverything else
catch-allFallback

Enabling/Disabling

APF is enabled by default. Disable with:

text
kube-apiserver --enable-priority-and-fairness=false

The Long-Running Exception

Some requests classified as "long-running" — such as remote command execution or log tailing — are not subject to APF. This is also true for --max-requests-inflight without APF.


8. The Aggregation Layer

The aggregation layer allows Kubernetes to be extended with additional APIs.

How It Works

The aggregation layer runs in-process with the kube-apiserver. When a request comes in for a registered API group, the main API server proxies it to the extension API server.

What Uses It

ExtensionAPI Group
metrics-servermetrics.k8s.io
Custom Metricscustom.metrics.k8s.io
Service Catalogservicecatalog.k8s.io
KubeVirtkubevirt.io

When to Use Aggregation vs CRDs

ApproachUse When
CRDsYou need custom resources with standard API behavior
AggregationYou need custom API semantics, subresources, or protocols

9. Leader Election

In an HA control plane, multiple instances of scheduler and controller-manager run, but only one is active.

How It Works

StepAction
1All instances try to acquire a Lease object in kube-system
2The winner becomes leader and does the work
3The leader periodically renews the lease
4If the leader dies, another instance acquires the lease

Both controller-manager and scheduler run three instances (one per control plane node). Leader election ensures only one does the work at a time.

Lease Parameters

ParameterDefaultMeaning
leaseDuration15sHow long the lease is valid
renewDeadline10sLeader must renew before this
retryPeriod2sHow often followers retry

The Failover Delay

If a leader dies, the new leader takes over after leaseDuration expires. Default: ~15 seconds. During this window, no reconciliation happens.

Graceful Leader Transition (Kubernetes 1.36+)

Previously, losing leadership meant os.Exit() and restart. Kubernetes 1.36 introduced graceful leader transition: on losing leadership, the component transitions to follower state and tries to become leader again, avoiding resource waste.


10. Version Skew Policy

Kubernetes components have version compatibility rules. Violating them causes subtle failures.

Supported Versions

The Kubernetes project maintains release branches for the most recent three minor releases. Example: 1.37, 1.36, 1.35.

Version Skew Rules

ComponentRule
kube-apiserver (HA)Newest and oldest instances within one minor version
kubeletMust not be newer than apiserver; up to 3 minor versions older (2 for < 1.25)
kube-proxyMust not be newer than apiserver; up to 3 minor versions older
kubectlWithin one minor version of apiserver (older or newer)

Examples

ScenarioSupported?
apiserver 1.37, kubelet 1.37✅
apiserver 1.37, kubelet 1.36✅
apiserver 1.37, kubelet 1.34✅
apiserver 1.37, kubelet 1.33❌
apiserver 1.37, kubelet 1.38❌ (newer)

The HA Narrowing Effect

If apiserver instances are at 1.37 and 1.36, kubelet is supported at 1.36, 1.35, and 1.34. Version 1.37 is not supported because that would be newer than the 1.36 apiserver instance.


11. Certificate Rotation

Control plane certificates expire. If they expire, the cluster breaks.

The Certificates

CertificateDefault Validity
kube-apiserver serving cert1 year
kube-apiserver client cert1 year
etcd serving cert1 year
etcd peer cert1 year
kubelet client cert1 year
kubelet serving cert1 year
CA certificate10 years

Rotation Methods

MethodDescription
kubeadmkubeadm certs renew all
kuceroAutomatic daemonset-based rotation
ManualRegenerate and replace certificates
Cloud-managedManaged by provider (EKS, GKE, AKS)

Kucero is a Kubernetes daemonset that performs automatic control plane certificate rotation.

The Rotation Procedure

  1. Plan a maintenance window (control plane will be briefly unavailable)
  2. Back up etcd and certificates
  3. Run rotation command
  4. Restart control plane components
  5. Verify cluster health

Warning: Certificate rotation may cause temporary unavailability when components restart. For production, perform during a maintenance window.


12. etcd Compaction and Defragmentation

Why etcd Grows

etcd's database file grows over time even when you're not adding objects. Compaction removes old revisions logically, but the bbolt backend does not shrink the file on disk. Without defragmentation, the file grows indefinitely.

The Two Operations

OperationWhat It Does
CompactionRemoves old revisions from the logical keyspace
DefragmentationReclaims disk space by removing gaps from deleted keys

Automatic Compaction

The Kubernetes API server passes --etcd-compaction-interval to trigger compaction periodically.

Manual Defragmentation

After compaction, defragment each etcd member:

bash
# Check fragmentation
etcdctl endpoint status --write-out=table

# Defragment one member at a time
etcdctl defrag --endpoints=https://etcd-1:2379

# Verify
etcdctl endpoint status --write-out=table

Warning: Defragmentation blocks the etcd member for the duration. Do one member at a time, never all at once.

Monitoring etcd Size

bash
# Database size
etcdctl endpoint status --write-out=table

# Alarm if DB size > 2 GB (default quota is 2 GB)
etcdctl alarm list

13. The Controller Pattern

The Informer Architecture

Controllers don't poll the API server. They use informers:

text
API Server
    │
    │ Watch
    ▼
┌─────────────────────────────────────────────────────────────┐
│  Informer                                                   │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    │
│  │  Reflector  │───►│  DeltaFIFO  │───►│  Indexer    │    │
│  │  (Watch)    │    │  (Queue)    │    │  (Cache)    │    │
│  └─────────────┘    └─────────────┘    └─────────────┘    │
│                                              │              │
│                                              ▼              │
│                                    ┌─────────────┐          │
│                                    │  Workqueue  │          │
│                                    │  (Rate-     │          │
│                                    │   limited)  │          │
│                                    └─────────────┘          │
└─────────────────────────────────────────────────────────────┘

The Four Components

ComponentPurpose
ReflectorWatches API server for changes
DeltaFIFOQueue of changes
IndexerLocal cache for fast reads
WorkqueueRate-limited work queue for the controller

Why This Design


14. Cloud Controller Manager

cloud-controller-manager integrates Kubernetes with cloud providers.

What It Does

ControllerCloud Integration
NodeAdds cloud metadata to Nodes
RouteConfigures cloud network routes
ServiceProvisions cloud load balancers
VolumeProvisions cloud storage

The Decoupling Principle

Before cloud-controller-manager, cloud-specific code lived in kube-controller-manager. This made Kubernetes less portable. Cloud-controller-manager decouples cloud logic from core Kubernetes.


1:1 copy of the class Google Doc, code in code blocks.