Stage 11, Part 2 of 9 · p. 93, Cluster Lifecycle & Operations

PART 2: ADVANCED CONCEPTS

6. Velero

Velero (formerly Heptio Ark) is the de-facto standard for Kubernetes workload backup and restore. It backs up Kubernetes objects and persistent volume data, and restores them to the same or a different cluster.

What Velero Backs Up

ComponentMethod
Kubernetes objectsAPI server export
Persistent volumesCSI snapshots or file-system backup
CRDsAPI server export
NamespacesSelective backup
SecretsEncrypted storage

Velero Architecture

text
Velero CLI → Velero Server (in-cluster) → Object Storage (S3, GCS, Azure Blob)
                     │
                     ├── Node Agent (DaemonSet) → PV data
                     └── CSI Snapshotter → Volume snapshots

Installing Velero

bash
velero install \
  --provider aws \
  --plugins velero/velero-plugin-for-aws:v1.14.0 \
  --bucket my-velero-backups \
  --backup-location-config region=us-east-1 \
  --snapshot-location-config region=us-east-1 \
  --secret-file ./credentials-velero

Backup and Restore

bash
# Create a backup
velero backup create production-backup --include-namespaces production

# Check status
velero backup describe production-backup
velero backup logs production-backup

# Restore
velero restore create --from-backup production-backup

# Schedule backups
velero schedule create daily-backup \
  --schedule="0 2 * * *" \
  --include-namespaces production \
  --ttl 168h  # 7-day retention

Velero Best Practices

PracticeWhy
Use schedules, not manual backupsConsistency
Set appropriate TTLCost control (7–30 days typical)
Verify backup contentCheck datauploads, not just Completed status
Test restores regularlyBackups without restores are useless
Store offsiteProtect against site failure
Encrypt backupsSecurity

The Critical Distinction: etcd vs Velero

The etcd snapshot is your control-plane insurance. Velero is your workload insurance and your only way to restore selectively or into a new cluster.


7. 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

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

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

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

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

etcd-defrag Tool

The community maintains etcd-defrag, a smarter defragmentation tool that:

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

Production rule: Alert when etcd DB size exceeds 1.5 GB. Defragment proactively.


8. Certificate Rotation

Kubernetes uses TLS certificates for all control plane communication. These certificates expire, and if they do, the cluster breaks.

Certificate Types and Validity

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
Managed servicesAutomatic (EKS, AKS, GKE)
Rancherrke certificate rotate
ManualRegenerate and replace

kubeadm Certificate Rotation

bash
# Check expiry
kubeadm certs check-expiration

# Rotate all
sudo kubeadm certs renew all

# Restart control plane components
sudo systemctl restart kubelet

Managed Service CA Rotation (2026)

Amazon EKS now supports certificate authority (CA) rotation with automated lifecycle management, enabling customers to rotate their cluster's CA through a managed lifecycle with automated safeguards.

Certificate Rotation Best Practices

PracticeWhy
Rotate before expiryAvoid cluster outage
Plan a maintenance windowControl plane briefly unavailable
Back up certificatesRollback safety
Test in stagingVerify procedure
Automate with managed servicesReduce operational burden

9. Cluster API (CAPI)

Cluster API (CAPI) is a Kubernetes sub-project that lets you manage the lifecycle of Kubernetes clusters using Kubernetes itself. You define a cluster in YAML, apply it to a management cluster, and CAPI controllers provision the infrastructure, bootstrap the nodes, and install Kubernetes.

CAPI Architecture

text
┌─────────────────────────────────────────────────────────────┐
│                    CLUSTER API ARCHITECTURE                 │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Management Cluster (runs CAPI controllers)         │   │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐ │   │
│  │  │ CAPI Core   │  │ Infra       │  │ Bootstrap   │ │   │
│  │  │ Controllers │  │ Provider    │  │ Provider    │ │   │
│  │  └─────────────┘  └─────────────┘  └─────────────┘ │   │
│  └─────────────────────────────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Workload Clusters                                  │   │
│  │  • Cluster 1 (AWS)                                  │   │
│  │  • Cluster 2 (vSphere)                              │   │
│  │  • Cluster 3 (bare metal)                           │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

The Four Layers

LayerPurposeExamples
CoreCluster and Machine abstractionsCluster, Machine, MachineSet
InfrastructureCloud resource provisioningAWSCluster, VSphereCluster
BootstrapTurn machine into K8s nodeKubeadmConfig, TalosConfig
Control PlaneManage control planeKubeadmControlPlane

CAPI v1.12 (January 2026)

The v1.12 release introduced in-place updates and chained upgrades:

CAPI Cluster Definition

yaml
apiVersion: cluster.x-k8s.io/v1beta1
kind: Cluster
metadata:
  name: production
spec:
  clusterNetwork:
    pods:
      cidrBlocks: ["192.168.0.0/16"]
  controlPlaneRef:
    apiVersion: controlplane.cluster.x-k8s.io/v1beta1
    kind: KubeadmControlPlane
    name: production-control-plane
  infrastructureRef:
    apiVersion: infrastructure.cluster.x-k8s.io/v1beta1
    kind: AWSCluster
    name: production

CAPI Strengths

StrengthWhy
ConsistencySame API across clouds
GitOps compatibilityYAML in version control
Automated upgradesCAPI sequences control plane upgrades
Multi-cloud37+ infrastructure providers

When to Use CAPI

ScenarioCAPI?
Multi-cloud fleet✅ Yes
On-prem + cloud✅ Yes
Single managed cluster❌ Use managed service
Small team❌ Use managed service

CAPI standardizes how clusters are created and managed, but it does little to improve how clusters behave in production or reduce operational friction for SREs. Use it when fleet consistency matters more than simplicity.


10. Multi-Cluster Management

Karmada

Karmada (Kubernetes Armada) is a CNCF-graduated project for multi-cluster, multi-cloud Kubernetes orchestration. It extends the standard Kubernetes API with centralized placement, propagation, failover, and multi-cluster autoscaling.

Karmada Architecture

ComponentPurpose
Karmada Control PlaneCentral API, scheduler, controllers
Member ClustersWorkload clusters (push or pull mode)
ResourceBindingWorkload distribution decisions
PropagationPolicyWhere workloads should run

Karmada v1.19 (2026)

The v1.19 release advances multi-component scheduling for distributed AI training jobs and promotes priority-based scheduling to Beta, enabled by default.

Karmada Use Cases

Use CaseDescription
Hybrid cloudRun workloads across AWS, GCP, on-prem
Multi-regionDistribute workloads globally
AI/ML trainingSchedule across GPU clusters
Disaster recoveryActive-active multi-cluster

Fleet (Rancher)

Fleet is Rancher's multi-cluster management tool. It deploys applications across clusters with GitOps.

Comparison

ToolApproachCNCF Status
KarmadaCentral control plane, propagation policiesGraduated
FleetGitOps-driven, Rancher-nativeIncubating
Cluster APIDeclarative cluster provisioningProduction-ready
vClusterVirtual clustersCNCF sandbox

11. Node Problem Detector

Node Problem Detector (NPD) is a DaemonSet that runs on every node. It monitors system logs, runs custom checks, and reports problems as node conditions or events that Kubernetes and operators can act upon.

What NPD Detects

Problem TypeExample
Kernel deadlocksHung tasks, soft lockups
Hardware failuresDisk errors, memory errors
Network problemsNIC down, packet loss
Resource pressureDisk, memory, PID pressure

NPD Architecture

text
NPD DaemonSet (per node)
    │
    ├── system-log-monitor (kernel logs)
    ├── custom-plugin-monitor (custom checks)
    └── kernel-monitor (kernel events)
    │
    ▼
API Server (NodeCondition + Events)
    │
    ▼
Scheduler / Autoscaler / Operators

Deploying NPD

yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: node-problem-detector
  namespace: kube-system
spec:
  selector:
    matchLabels:
      app: node-problem-detector
  template:
    metadata:
      labels:
        app: node-problem-detector
    spec:
      hostNetwork: true
      containers:
      - name: node-problem-detector
        image: registry.k8s.io/node-problem-detector/node-problem-detector:v0.8.19
        securityContext:
          privileged: true
        volumeMounts:
        - name: log
          mountPath: /var/log
          readOnly: true

12. Disaster Recovery Strategy

RTO and RPO

MetricDefinitionDepends On
RTO (Recovery Time Objective)Maximum acceptable downtimeRecovery speed
RPO (Recovery Point Objective)Maximum acceptable data lossBackup frequency

The Four Recovery Layers

For a recovery to count, four layers must come back:

  1. Cluster infrastructure (nodes, networking)
  2. Cluster state (etcd / API objects)
  3. Persistent data (volumes)
  4. Traffic path (DNS, ingress, load balancers)

Recovery fails at the joins between the layers: a restored cluster with no data, restored data with no traffic path, an application definition that provisions an empty volume.

DR Strategy Matrix

StrategyRPORTOCost
Backup/RestoreHoursHours$
SnapshotMinutesMinutes$$
ReplicationSecondsMinutes$$$
Active-ActiveZeroZero$$$$

DR Testing

TestFrequency
Restore etcd snapshotMonthly
Restore from VeleroMonthly
Full cluster rebuildQuarterly
Multi-region failoverQuarterly

13. Infrastructure as Code for Clusters

Terraform for Cluster Provisioning

hcl
resource "aws_eks_cluster" "production" {
  name     = "production"
  role_arn = aws_iam_role.eks.arn
  version  = "1.36"

  vpc_config {
    subnet_ids = aws_subnet.private[*].id
  }
}

resource "aws_eks_node_group" "workers" {
  cluster_name    = aws_eks_cluster.production.name
  node_group_name = "workers"
  node_role_arn   = aws_iam_role.nodes.arn
  subnet_ids      = aws_subnet.private[*].id
  instance_types  = ["m5.xlarge"]
  scaling_config {
    desired_size = 3
    max_size     = 10
    min_size     = 1
  }
}

Crossplane for Kubernetes-Native Infrastructure

Crossplane extends Kubernetes to manage cloud resources as CRDs. Instead of Terraform, you define cloud resources as Kubernetes objects.

yaml
apiVersion: rds.aws.upbound.io/v1beta1
kind: Instance
metadata:
  name: production-db
spec:
  forProvider:
    region: us-east-1
    instanceClass: db.t3.medium
    engine: postgres
    allocatedStorage: 100

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