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
| Mechanism | What It Extends | Use Case |
| Custom Resource Definitions (CRDs) | The API | New resource types |
| Admission Webhooks | The request pipeline | Validation, mutation |
| Aggregation Layer | The API server | Full custom API servers |
Why Extensibility Matters
| Without Extensibility | With Extensibility |
| Fork Kubernetes for new features | Add features via CRDs |
| Wait for upstream releases | Ship features independently |
| Limited to core resources | Unlimited custom resources |
| No domain-specific automation | Operators 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:
| Validation | Example |
| Type | type: string |
| Required | required: [image, replicas] |
| Minimum/Maximum | minimum: 1, maximum: 100 |
| Pattern | pattern: "^[a-z0-9-]+$" |
| Enum | enum: [dev, staging, prod] |
| Default | default: 1 |
CRD Scopes
| Scope | Behavior |
| Namespaced | CRs exist in namespaces |
| Cluster | CRs are cluster-wide |
CRD Best Practices
| Practice | Why |
| Use OpenAPI schema | Validation, documentation |
| Enable status subresource | Separate spec from status |
| Set additionalPrinterColumns | Better kubectl get output |
| Use shortNames | Convenience |
| Version from the start | Plan for evolution |
| Avoid over-nesting | Keep 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:
- Watches the API server for changes to specific resources
- Maintains a local cache (Indexer) for fast reads
- 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:
| Feature | Purpose |
| Rate limiting | Prevents overwhelming the controller |
| Deduplication | Collapses multiple events for the same object |
| Retry | Re-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
| Guarantee | Meaning |
| Level-triggered | Reconcile runs on the current state, not events |
| Idempotent | Running multiple times produces the same result |
| Eventually consistent | The system converges to desired state |
| Optimistic concurrency | Uses 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 Controller | Operator |
| Manages one resource type | Manages a complex application |
| Generic logic | Domain-specific knowledge |
| No external coordination | Coordinates multiple resources |
| Example: ReplicaSet controller | Example: 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
| Operation | What It Does |
| Deployment | Creates and configures all resources |
| Scaling | Adjusts replicas based on load |
| Backup | Scheduled backups to object storage |
| Restore | Point-in-time recovery |
| Upgrade | Orchestrates rolling upgrades |
| Failover | Promotes replicas on primary failure |
| Configuration | Manages config changes safely |
Operator Maturity Model
| Level | Capability |
| 1. Basic Install | Automated provisioning |
| 2. Seamless Upgrades | Patch and minor upgrades |
| 3. Full Lifecycle | Backup, restore, failover |
| 4. Deep Insights | Metrics, alerts, logs |
| 5. Auto Pilot | Auto-scaling, auto-tuning, auto-recovery |
When to Build an Operator
| Scenario | Build 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
| Operator | Purpose |
| Prometheus Operator | Manages Prometheus, Alertmanager, ServiceMonitors |
| cert-manager | Automates TLS certificate management |
| Istio Operator | Manages Istio service mesh |
| PostgreSQL Operator | Manages PostgreSQL clusters |
| Kafka Operator | Manages Kafka clusters |
| Crossplane | Manages cloud resources from Kubernetes |
1:1 copy of the class Google Doc, code in code blocks.