Stage 9, Part 1 of 9, Cluster Extensibility (CRDs, Controllers, Operators)

Text

PART 1: CORE THEORY

1. What is Cluster Extensibility?

Kubernetes is designed to be extended. The core API is intentionally limited, and the extension mechanisms allow you to add new resource types, new controllers, and new behaviors without modifying Kubernetes itself.

The Three Extension Mechanisms

MechanismWhat It ExtendsUse Case
Custom Resource Definitions (CRDs)The APINew resource types
Admission WebhooksThe request pipelineValidation, mutation
Aggregation LayerThe API serverFull custom API servers

Why Extensibility Matters

Without ExtensibilityWith Extensibility
Fork Kubernetes for new featuresAdd features via CRDs
Wait for upstream releasesShip features independently
Limited to core resourcesUnlimited custom resources
No domain-specific automationOperators for every use case

The Extensibility Spectrum

text
Simple                          Complex
  │                                │
  ▼                                ▼
CRDs only  →  CRDs + Webhooks  →  Full Operators  →  Aggregated APIs

Rule of thumb: Start with CRDs. Add webhooks when you need validation. Build an Operator when you need automation.


2. Custom Resource Definitions (CRDs)

A Custom Resource Definition (CRD) extends the Kubernetes API with your own resource type. Once installed, your custom resources behave like built-in Kubernetes resources.

CRD Architecture

text
┌─────────────────────────────────────────────────────────────┐
│                    CRD ARCHITECTURE                         │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Kubernetes API                                     │   │
│  │  ┌─────────────┐    ┌─────────────────────────────┐ │   │
│  │  │ CRD         │───►│ Extended API                │ │   │
│  │  │ Definition  │    │ • /apis/example.com/v1/     │ │   │
│  │  └─────────────┘    │   webapps                   │ │   │
│  │                     └─────────────────────────────┘ │   │
│  └─────────────────────────────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Custom Resources (CRs)                             │   │
│  │  • my-webapp                                        │   │
│  │  • my-database                                      │   │
│  └─────────────────────────────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Controller (Watch → Reconcile → Manage)            │   │
│  │  • Watches CR events                                │   │
│  │  • Reconciles desired vs actual state               │   │
│  │  • Creates/updates Deployments, Services, etc.      │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

A Basic CRD

yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: webapps.example.com          # <plural>.<group>
spec:
  group: example.com
  names:
    kind: WebApp
    listKind: WebAppList
    plural: webapps
    singular: webapp
    shortNames:
    - wa
  scope: Namespaced                   # or Cluster
  versions:
  - name: v1
    served: true                      # API version enabled
    storage: true                     # Primary storage version
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            required:
            - image
            - replicas
            properties:
              image:
                type: string
                description: Container image
              replicas:
                type: integer
                minimum: 1
                maximum: 100
                default: 1
              port:
                type: integer
                default: 8080
          status:
            type: object
            properties:
              availableReplicas:
                type: integer
              conditions:
                type: array
                items:
                  type: object
                  properties:
                    type:
                      type: string
                    status:
                      type: string
                    lastTransitionTime:
                      type: string
                      format: date-time
    additionalPrinterColumns:         # Extra columns for kubectl get
    - name: Image
      type: string
      jsonPath: .spec.image
    - name: Replicas
      type: integer
      jsonPath: .spec.replicas
    - name: Available
      type: integer
      jsonPath: .status.availableReplicas
    - name: Age
      type: date
      jsonPath: .metadata.creationTimestamp
    subresources:
      status: {}                      # Enable status subresource
      # scale:                        # Enable scale subresource
      #   specReplicasPath: .spec.replicas
      #   statusReplicasPath: .status.availableReplicas

Creating a Custom Resource

yaml
apiVersion: example.com/v1
kind: WebApp
metadata:
  name: my-webapp
  namespace: production
spec:
  image: nginx:1.25
  replicas: 3
  port: 80

CRD Validation

CRDs use OpenAPI v3 schema for validation:

ValidationExample
Typetype: string
Requiredrequired: [image, replicas]
Minimum/Maximumminimum: 1, maximum: 100
Patternpattern: "^[a-z0-9-]+$"
Enumenum: [dev, staging, prod]
Defaultdefault: 1

CRD Scopes

ScopeBehavior
NamespacedCRs exist in namespaces
ClusterCRs are cluster-wide

CRD Best Practices

PracticeWhy
Use OpenAPI schemaValidation, documentation
Enable status subresourceSeparate spec from status
Set additionalPrinterColumnsBetter kubectl get output
Use shortNamesConvenience
Version from the startPlan for evolution
Avoid over-nestingKeep schemas simple

3. The Controller Pattern

A controller is a control loop that watches resources and reconciles the desired state with the actual state.

The Watch-Queue-Reconcile Pattern

text
┌─────────────────────────────────────────────────────────────┐
│                    CONTROLLER PATTERN                       │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Informer                                           │   │
│  │  • Watches API server for changes                   │   │
│  │  • Maintains local cache                            │   │
│  │  • Enqueues events to WorkQueue                     │   │
│  └──────────────────────┬──────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  WorkQueue                                          │   │
│  │  • Rate-limited queue                               │   │
│  │  • Deduplicates events                              │   │
│  │  • Retries failed items                             │   │
│  └──────────────────────┬──────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Reconciler (Worker Goroutines)                     │   │
│  │  • Processes one item at a time                     │   │
│  │  • Reads current state from cache                   │   │
│  │  • Compares desired vs actual                       │   │
│  │  • Acts to reconcile                                │   │
│  │  • Updates status                                   │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

The Informer

The Informer is the core of the controller pattern. It:

  1. Watches the API server for changes to specific resources
  2. Maintains a local cache (Indexer) for fast reads
  3. Enqueues events to the WorkQueue via event handlers

Informers watch the API server and mirror objects into a local cache. Event handlers boil every change down to a small key that means "go reconcile this thing."

The WorkQueue

The WorkQueue decouples event reception from processing. It provides:

FeaturePurpose
Rate limitingPrevents overwhelming the controller
DeduplicationCollapses multiple events for the same object
RetryRe-queues failed items with backoff

The RateLimitingInterface extends DelayingInterface with rate limiter functionality. When the number of insertions exceeds the rate limiter rules, the object is pushed to a delayed queue for processing.

The Reconciler

The Reconciler contains the actual logic:

go
func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    // 1. Fetch the custom resource
    var webapp examplev1.WebApp
    if err := r.Get(ctx, req.NamespacedName, &webapp); err != nil {
        if apierrors.IsNotFound(err) {
            return ctrl.Result{}, nil  // Resource deleted
        }
        return ctrl.Result{}, err
    }

    // 2. Check if deployment exists
    var deployment appsv1.Deployment
    err := r.Get(ctx, types.NamespacedName{
        Name:      webapp.Name,
        Namespace: webapp.Namespace,
    }, &deployment)

    if apierrors.IsNotFound(err) {
        // 3. Create deployment
        deployment = r.deploymentForWebApp(&webapp)
        if err := r.Create(ctx, &deployment); err != nil {
            return ctrl.Result{}, err
        }
        return ctrl.Result{Requeue: true}, nil
    }

    if err != nil {
        return ctrl.Result{}, err
    }

    // 4. Update deployment if needed
    if r.needsUpdate(&deployment, &webapp) {
        r.updateDeployment(&deployment, &webapp)
        if err := r.Update(ctx, &deployment); err != nil {
            return ctrl.Result{}, err
        }
    }

    // 5. Update status
    webapp.Status.AvailableReplicas = deployment.Status.AvailableReplicas
    if err := r.Status().Update(ctx, &webapp); err != nil {
        return ctrl.Result{}, err
    }

    return ctrl.Result{}, nil
}

The Reconciliation Guarantees

GuaranteeMeaning
Level-triggeredReconcile runs on the current state, not events
IdempotentRunning multiple times produces the same result
Eventually consistentThe system converges to desired state
Optimistic concurrencyUses resourceVersion for conflict detection

The Operator Pattern

An Operator is a controller for a specific application. It encodes the Day 2 operations that a human operator would perform.

Standard ControllerOperator
Manages one resource typeManages a complex application
Generic logicDomain-specific knowledge
No external coordinationCoordinates multiple resources
Example: ReplicaSet controllerExample: PostgreSQL operator

Operators extend Kubernetes to manage complex applications automatically. Instead of writing scripts and runbooks, you encode operational knowledge into code that runs in your cluster.

Operators were introduced to address Day 2 operations such as backups, version upgrades, and automated failure recovery.


4. Operators

An Operator is a controller that encodes human operational knowledge for a specific application.

What Operators Automate

OperationWhat It Does
DeploymentCreates and configures all resources
ScalingAdjusts replicas based on load
BackupScheduled backups to object storage
RestorePoint-in-time recovery
UpgradeOrchestrates rolling upgrades
FailoverPromotes replicas on primary failure
ConfigurationManages config changes safely

Operator Maturity Model

LevelCapability
1. Basic InstallAutomated provisioning
2. Seamless UpgradesPatch and minor upgrades
3. Full LifecycleBackup, restore, failover
4. Deep InsightsMetrics, alerts, logs
5. Auto PilotAuto-scaling, auto-tuning, auto-recovery

When to Build an Operator

ScenarioBuild Operator?
Complex stateful app✅ Yes
Multi-step workflows✅ Yes
Auto-remediation✅ Yes
Simple stateless app❌ No (use Deployment)
One-time setup❌ No (use Job)
Simple config change❌ No (use ConfigMap)

Operators are best for long-lived, stateful responsibilities. Use them when you need continuous reconciliation: if resources drift or are deleted, the operator enforces desired state.

Real-World Operators

OperatorPurpose
Prometheus OperatorManages Prometheus, Alertmanager, ServiceMonitors
cert-managerAutomates TLS certificate management
Istio OperatorManages Istio service mesh
PostgreSQL OperatorManages PostgreSQL clusters
Kafka OperatorManages Kafka clusters
CrossplaneManages cloud resources from Kubernetes

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