Kubernetes CRDs and Operators: Build Your Own API Safely
Kubernetes CRDs and operators extend the Kubernetes API with your own resource types and a controller that reconciles them. This lesson covers schema design, status, finalizers, RBAC, versioning, conversion, testing, and upgrade safety so a custom API survives production instead of becoming an unowned script.
Introduction
Kubernetes CRDs and operators let a platform team teach the API server a new object type and run a controller that keeps real infrastructure matching it. This lesson designs the schema, reconciliation loop, permissions, and upgrade path so your custom API behaves like a built-in resource instead of a fragile script with YAML attached.
Illustrative composite: a platform team ships a Database custom resource so application teams stop hand-writing StatefulSets. The first version accepts any string for engine version, stores status inside spec, and grants the controller cluster-admin because narrowing permissions felt slow. Six months later a typo creates a database the controller cannot delete, an upgrade renames a field, and old objects fail validation on every GitOps sync. Nothing here was exotic. The API was treated as a config file, not a contract.
This is a late lesson in the Kubernetes roadmap series. The previous lesson covered Helm and Kustomize in GitOps pipelines, where teams package and render manifests. A custom API goes one step further: instead of rendering known objects, you define a new object and own its lifecycle. That is powerful, and it is also a long-term commitment. Users will store objects, build automation on your fields, and expect upgrades not to break them.
The 5-minute takeaway
Start with the user-facing contract, not the controller code. Name the resource, write a strict schema with a separate status, decide who may create and delete it, and plan how version two will coexist with version one. Then write a level-triggered reconciliation loop that is safe to run twice, grants the controller only the permissions it uses, and reports progress through conditions users can read with kubectl describe.
1. Kubernetes CRDs and operators: the two halves of a custom API
Kubernetes CRDs and operators split into an API half and a control half. The CustomResourceDefinition registers a new kind, its schema, and its versions with the API server. The operator is a controller that watches those objects and reconciles the cluster toward the state each object describes, the same pattern built-in controllers use.
A CRD on its own does nothing except store and validate objects. You can apply a CRD, create custom resources, and watch them sit unchanged forever, because no controller is acting on them. That surprises teams the first time: the API server happily accepts the object, kubectl get lists it, and nothing happens. The operator supplies the behaviour. It observes desired state, compares it with actual state, and takes the smallest safe step toward closing the gap.
Think of the CRD as the contract and the operator as the employee who honours it. The contract defines names, fields, validation, and versions. The employee creates child objects, updates them when the spec changes, cleans up on deletion, and reports status. Keeping those halves separate in your head prevents a common design error: stuffing behaviour hints into the schema, such as fields that only make sense to one controller version, then being unable to change them later.
Not every automation needs this machinery. If a Helm chart or a Kustomize overlay can express the variation, use that; the previous lesson on packaging covers that ground. Reach for a custom API when the resource has a real lifecycle: it needs status, it owns child objects, it must react to drift, or users should describe an outcome such as a database with backups rather than assemble twelve manifests correctly every time.
2. Kubernetes CRDs and operators: naming, group, and scope
Kubernetes CRDs and operators start with naming that you cannot easily change later. Choose an API group you control, a plural name that reads well in kubectl get, and a scope that matches the resource lifecycle. Namespaced resources suit tenant-owned objects; cluster-scoped resources suit platform-wide objects that administrators manage deliberately.
platform.example.com, rather than inventing apps or borrowing kubernetes.io. The CRD name must be <plural>.<group>, for example databases.platform.example.com. Short names help humans, so add one or two that will not collide with existing resources. Renaming a group or plural later means a new CRD and a migration of every stored object, which is why this decision deserves ten minutes of argument now.
Scope decides blast radius. A namespaced resource lives inside a namespace, inherits namespace RBAC boundaries, and can be owned by namespace-scoped controllers. Most application-facing resources should be namespaced. Cluster-scoped resources are visible everywhere and usually need cluster-level permissions to manage, which makes them right for things like node pools or cluster-wide policies and wrong for a team's database. When unsure, start namespaced; widening scope later is a migration, but so is narrowing it.
| Decision | Namespaced | Cluster-scoped |
|---|---|---|
| Typical owner | Application team in its namespace | Platform team for the whole cluster |
| RBAC boundary | Namespace Role and RoleBinding | ClusterRole and ClusterRoleBinding |
| Good fit | Database, queue, tenant app | Node pool, cluster policy, shared gateway |
| Risk if wrong | Cross-namespace needs get awkward | Tenant objects gain cluster-wide reach |
Also decide the singular, list kind, and categories early. Categories let kubectl get all include your resource where appropriate. These details sound cosmetic until an on-call engineer at 3 a.m. cannot find the object type during an incident. A custom API should feel native: discoverable through kubectl api-resources, readable in kubectl get, and explainable through kubectl explain.
3. Kubernetes CRDs and operators: schema design that ages well
Kubernetes CRDs and operators live or die by schema design, because stored objects outlive the code that wrote them. Use an OpenAPI v3 schema with required fields, enums, numeric bounds, and patterns so invalid objects are rejected at apply time. Keep spec for desired state and status for observed state, never mixed.
Validation at the API server is your cheapest safety net. A field such as replicas should carry minimum and maximum bounds. An engine version should be an enum or a pattern, not a free string that accepts latest and 15.x-typo with equal enthusiasm. Required fields should be genuinely required; every optional field needs a documented default behaviour, and defaulting should happen in one place so users can predict the effective value.
Avoid x-kubernetes-preserve-unknown-fields except where you truly accept arbitrary maps, because it disables the validation that protects users from typos. A misspelled field that is silently stored and ignored is worse than a rejected apply: the user believes the setting took effect. Strict schemas turn silent no-ops into immediate, fixable errors, which is exactly the behaviour built-in resources give you.
4. Kubernetes CRDs and operators: status, conditions, and printer columns
Kubernetes CRDs and operators should report observed state through the status subresource, using standard conditions such as Ready, Progressing, and Degraded. Status is written by the controller, not by users, and the subresource enforces that split. Add printer columns so kubectl get shows readiness and age without forcing users into JSON.
The status subresource matters because it separates permissions and update paths. A normal update cannot change status, and a status update cannot change spec. That prevents a user edit from wiping controller-reported state and prevents the controller from accidentally rewriting user intent. Enable it from the first version; adding it later changes update semantics for existing clients and GitOps tooling.
Conditions are the contract between your controller and every human or tool watching it. Use the standard shape: type, status, reason, message, lastTransitionTime, and observedGeneration. The observedGeneration field is the detail teams skip and regret, because without it a Ready condition from before the last spec change looks current. A user who edits the spec and immediately checks status should be able to tell whether the controller has even seen the new generation yet.
Printer columns turn kubectl get databases into a usable dashboard. Show ready replicas, engine, and age. Keep columns few and stable; adding columns is safe, renaming them breaks scripts that parse table output, although scripts should use JSON anyway. Good status design is what makes an operator feel trustworthy during an incident, when nobody has time to read controller logs first.
5. Kubernetes CRDs and operators: the reconciliation loop
Kubernetes CRDs and operators work through reconciliation: read the desired object, read the actual cluster state, compute the difference, and act to close it. The loop must be level-triggered and idempotent, meaning it reacts to current state rather than events, and running it twice in a row produces the same result as running it once.
Level-triggered design is the difference between a controller and a script. A script reacts to a create event and hopes it never misses one. A controller lists current state on every pass, so a missed event, a restart, or a manual edit by an administrator all converge back to the desired state. Design every reconcile as if it could run at any moment with no memory of the previous run, because after a leader election or a crash, it will.
Idempotence means each action checks before it writes. Create the child Deployment only if it does not exist; update it only if the spec differs; use server-side apply or careful patching so repeated reconciles do not fight other managers. A controller that updates an object on every pass will hot-loop, churn resource versions, and flood the API server. Compare before writing, and treat no-change as the normal case.
Reconcile should also be partial-failure friendly. If creating the Service succeeds and creating the backup job fails, the next pass should finish the job, not start over or wedge. Return an error or a requeue with backoff for transient failures, and write a Degraded condition for failures a human must fix, such as an invalid referenced Secret. The loop's job is convergence, not perfection on the first attempt.
6. Kubernetes CRDs and operators: ownership, finalizers, and deletion
Kubernetes CRDs and operators must handle deletion as carefully as creation. Set owner references on child objects so garbage collection removes them with the parent. Use finalizers only when cleanup needs work outside the cluster, such as releasing an external database, and always make finalizer handling idempotent and time-bounded in behaviour.
Owner references are the default cleanup mechanism and they are free. When the parent custom resource is deleted, the garbage collector deletes owned children, respecting foreground or background propagation. Set controller: true on the managing owner reference and block owner deletion where ordering matters. Teams that skip owner references end up writing cleanup code for objects Kubernetes would have removed automatically, then debugging why orphaned Services accumulate.
Finalizers are for the cases garbage collection cannot reach: an external cloud resource, a DNS record, a licence seat. A finalizer blocks deletion until your controller removes it, which means a broken controller can wedge namespaces in Terminating for days. Keep finalizer logic small, make it safe to run repeatedly, and log loudly when it cannot complete. Never add a finalizer for work that owner references already cover.
Deletion also needs a story for data. Deleting a Database object should probably not silently destroy the underlying volume. Decide the retention behaviour, expose it in the spec with a safe default such as retain, and document it where users will see it before they delete. The storage lesson on StatefulSet patterns covers retain behaviour for volumes; the same caution applies when your controller owns the data path.
7. Kubernetes CRDs and operators: RBAC for the controller
Kubernetes CRDs and operators need controller permissions scoped to exactly what reconciliation does. Grant verbs per resource and subresource, prefer namespace-scoped Roles where the operator watches one namespace, and treat cluster-wide grants as a design decision to defend. A compromised operator with cluster-admin is a cluster compromise with extra steps.
Write the RBAC from the reconcile code outward. List every API call the controller makes: get, list, and watch the custom resource; create and update Deployments and Services; update the status subresource; read referenced Secrets. Each call becomes a rule. If the code never deletes Secrets, the Role must not grant it. Reviewers should be able to diff the RBAC against the code and find no surplus.
Watch scope drives binding scope. An operator managing one namespace can run with a Role in that namespace, which keeps its blast radius small. A cluster-wide operator needs ClusterRole rules for namespaced resources across namespaces, which is legitimate for platform controllers but should still avoid wildcards. The Kubernetes RBAC lesson covers subjects, bindings, and escalation paths in depth; apply the same least-privilege discipline to your controller's ServiceAccount.
Users need RBAC too. Decide who may create, update, and delete the custom resource, and who may only read it. Remember that permission to create a powerful custom resource is permission to trigger everything the controller will do with it. If your Database resource can request large storage or privileged settings, namespace admins who can create it effectively hold those powers. Design user-facing RBAC as part of the API, not as an afterthought.
8. Kubernetes CRDs and operators: versioning and conversion
Kubernetes CRDs and operators must plan for version two on day one. Serve multiple versions when the schema changes, keep exactly one storage version, and write conversion logic that moves objects between versions without losing data. Never break stored objects by renaming or retyping fields inside an existing version.
Start at v1alpha1 while the API is young, and say plainly that alpha means fields may change. The mistake is calling the first draft v1 to look mature, then discovering you need to change a field type. Version names are a promise. Alpha and beta versions let you learn from real users before the promise hardens, and Kubernetes conventions give you that vocabulary for free.
When a new version arrives, the API server stores objects in the storage version and converts on read and write. Conversion webhooks handle anything beyond trivial field additions. The dangerous changes are renames, type changes, and fields that exist in one version but not another; conversion must round-trip without silent data loss, or an object read as v1 and written back as v2 loses settings. Test conversion with stored objects from the old version, not just fresh examples.
Migration is part of the release, not a cleanup task for later. Move the storage version, run a storage version migration so every stored object is rewritten, and only then drop the old served version. Skipping migration leaves objects stored in a version you later remove, which makes them unreadable. Treat the sequence as a runbook with a verification step: list objects, confirm the stored version, then retire the old one.
9. Kubernetes CRDs and operators: webhooks, defaults, and guardrails
Kubernetes CRDs and operators can add mutating and validating webhooks for defaults and cross-field rules that schema alone cannot express. Keep webhooks fast, deterministic, and fail-closed only where safety demands it. Prefer schema validation and CEL rules first, because every webhook is another component that can block writes when it is down.
Schema validation handles single-field rules well: types, bounds, enums, patterns. Cross-field rules, such as replicas above three requiring a backup schedule, need CEL validation rules in the CRD or a validating webhook. CEL rules live with the CRD and run inside the API server, so prefer them where they fit. Webhooks remain useful for checks against other objects, such as confirming a referenced Secret exists, but that coupling makes applies fail when dependencies are temporarily missing.
Defaulting deserves the same discipline. A mutating webhook or CRD default that fills in a field should be visible to users after apply, so kubectl get -o yaml shows the effective value. Hidden defaults that only the controller knows about create the worst debugging experience: the stored object disagrees with running behaviour. Default in the open, document the defaults, and treat a changed default as an API change that needs a version note.
| Guardrail | Use it for | Watch out for |
|---|---|---|
| OpenAPI schema | Types, bounds, enums, required fields | Overly strict patterns that reject valid input |
| CEL rules | Cross-field checks inside the object | Complex rules nobody can debug |
| Validating webhook | Checks against other objects or policy | Webhook outage blocking all writes |
| Mutating webhook | Defaults users should see stored | Silent changes that surprise GitOps diffs |
Set webhook failure policy deliberately. failurePolicy: Fail protects safety-critical validation but turns a webhook outage into an API outage for that resource. Ignore keeps writes flowing but admits unvalidated objects. For most platform APIs, fail closed on validation that prevents data loss, fail open on cosmetic checks, and monitor webhook latency and errors like any production dependency.
10. Kubernetes CRDs and operators: testing like a platform team
Kubernetes CRDs and operators need tests at three levels: schema tests that reject bad objects, reconcile tests that prove convergence and idempotence, and upgrade tests that load objects stored by the previous version. Run controller tests against a real API server environment such as envtest or a disposable kind cluster, not only mocks.
Schema tests are cheap and catch embarrassing releases. Apply objects with missing required fields, out-of-range replicas, and misspelled field names, and assert the API server rejects them. Also assert that a valid minimal object is accepted, because an over-strict schema that rejects everything is a production incident wearing a safety costume. Keep these fixtures in the repo beside the CRD so schema changes update tests in the same commit.
Reconcile tests should cover the unhappy paths: child object deleted manually, spec changed mid-flight, referenced Secret missing, controller restarted between steps. The assertion that matters is convergence: after enough reconciles, actual state matches desired state and status says Ready with the current generation. Test idempotence explicitly by reconciling twice and asserting the second pass makes no writes.
Upgrade tests protect your users from your roadmap. Store objects with the old version, upgrade the CRD and controller, and confirm the objects still read correctly, reconcile, and report status. The local lab lesson on kind clusters gives a disposable environment for exactly this kind of rehearsal. An operator that has never been upgrade-tested will eventually upgrade-test itself in production, on a Friday.
11. Kubernetes CRDs and operators: rollout, observability, and failure modes
Kubernetes CRDs and operators should roll out like any production controller: leader election for replicas, metrics on reconcile errors and latency, structured logs keyed by object, and alerts on degraded conditions. Ship CRD changes before controller changes that depend on them, and keep the previous controller able to read new objects during the transition.
Run at least two controller replicas with leader election so a node loss does not stop reconciliation. Only the leader acts; the standby takes over through the Lease. Without leader election, two replicas reconcile the same object and fight, producing flapping status and duplicate writes. Leader election is standard in controller-runtime and Operator SDK scaffolds, so there is little excuse for skipping it.
Observability should answer three questions fast: is the controller running, is it keeping up, and which objects are stuck? Export reconcile counts, error counts, and queue depth. Log with namespace, name, and generation so one object's history can be followed. Alert on objects sitting in Degraded beyond a threshold, because a custom resource stuck for a day usually means a user is waiting on your platform and does not know it.
| Symptom | First check | Likely cause | Fix direction |
|---|---|---|---|
| Custom resource never changes | Controller Pod logs and leader Lease | Controller down, or no leader elected | Restore controller; verify leader election |
| Object stuck deleting | Finalizers on the object | Finalizer owner dead or cleanup failing | Fix cleanup path; remove finalizer only after external state is safe |
| Status flaps between values | Controller replica count and Lease holder | Two replicas reconciling without leader election | Enable leader election; stop duplicate writes |
| Apply rejected with schema errors | Validation message field path | Schema stricter than stored objects | Loosen additively in a new version; migrate stored objects |
| Old objects fail after upgrade | Storage version and conversion webhook logs | Stored version changed without migration | Run storage migration; fix conversion round-trip |
| Controller hot-loops on one object | Reconcile rate and status write diff | Non-idempotent reconcile writing status every pass | Compare before writing; skip no-change updates |
Rollout order matters. Apply the new CRD first so the API server accepts new fields, then roll the controller. Reversing the order makes the new controller write objects the old schema rejects. During the transition, the old controller version must tolerate objects written with new fields, which is another argument for additive schema changes inside a version and strict changes only across versions. Teams delivering through GitOps should apply the same order in Git, as covered in GitOps best practices: the CRD commit lands and syncs before the controller commit that depends on it.
12. Kubernetes CRDs and operators: production checklist
Kubernetes CRDs and operators are ready for production when the contract, controller, permissions, and upgrade path have each been reviewed as separate risks. Use the checklist below before the first real team depends on your API, because after adoption every shortcut becomes a migration someone else has to schedule around.
Adoption changes the cost of everything. Before users arrive, renaming a field is an edit. After users arrive, it is a version bump, a conversion webhook, a storage migration, and a communication plan. The checklist below is ordered so the irreversible decisions come first: names, scope, schema, and storage version. Controller polish can iterate weekly; the API surface cannot.
- [ ] Group, plural, kind, and scope reviewed as permanent decisions
- [ ] Schema rejects invalid objects; status subresource enabled; conditions carry observedGeneration
- [ ] Reconcile is level-triggered and idempotent; second pass makes no writes
- [ ] Owner references set on children; finalizers only for external cleanup
- [ ] Controller RBAC matches API calls in code; user RBAC designed per namespace
- [ ] Versioning plan written: alpha honesty, conversion tests, storage migration steps
- [ ] Upgrade test passes with objects stored by the previous version
- [ ] Leader election, metrics, and Degraded alerts in place before first adopter
The next lesson moves from extending the API to operating the cluster underneath it: kubeadm cluster administration covers joining, draining, upgrading, and recovering nodes. That pairing is deliberate. A custom API is only as reliable as the control plane storing it, and the engineers who build operators should also know how the cluster itself is maintained.
Frequently Asked Questions
What is the difference between a CRD and a custom resource in Kubernetes CRDs and operators?
A CustomResourceDefinition registers a new type with the API server, including its group, names, scope, schema, and versions. A custom resource is one object of that type, such as a single Database named payments. The CRD is the blueprint installed once by platform teams; custom resources are the instances users create, update, and delete every day.
Do Kubernetes CRDs and operators need a controller to do anything useful?
Yes. A CRD alone only stores and validates objects; nothing acts on them. The operator's controller watches custom resources and reconciles real objects such as Deployments, Services, and volumes toward the desired state. Without a controller, a custom resource is just structured data sitting in etcd, visible in kubectl but inert.
How should Kubernetes CRDs and operators separate spec and status?
Put desired state in spec, written by users, and observed state in status, written only by the controller through the status subresource. Status should use standard conditions with reason, message, and observedGeneration so readers can tell whether the controller has processed the latest spec. Mixing observed values into spec causes update conflicts and confusing GitOps diffs.
What permissions do Kubernetes CRDs and operators controllers actually need?
Only the API calls the reconcile code makes: typically get, list, and watch on the custom resource, create and update on the child objects it manages, and update on the status subresource. Avoid wildcards and cluster-admin. Scope bindings to the namespaces the operator watches, and review RBAC against the code whenever reconciliation gains a new action.
How do Kubernetes CRDs and operators handle a new API version safely?
Serve the new version alongside the old one, keep one storage version, and provide conversion that round-trips objects without losing fields. Test with objects stored by the previous version, migrate stored objects to the new storage version, and only then stop serving the old version. Renaming or retyping fields inside an existing version breaks stored objects.
When should a team choose Kubernetes CRDs and operators over Helm or Kustomize?
Choose a custom API when the resource has a lifecycle: it owns child objects, reports status, reacts to drift, or hides multi-step operations such as backups and failover. Choose Helm or Kustomize when the variation is just rendering known manifests with different values. Packaging is cheaper to maintain; an operator is a long-term API commitment.
Why do Kubernetes CRDs and operators controllers use finalizers?
Finalizers block deletion until the controller finishes cleanup that garbage collection cannot do, such as releasing an external database or DNS record. They should be rare, idempotent, and quick, because a broken controller holding a finalizer can wedge a namespace in Terminating. For in-cluster children, owner references handle cleanup without finalizers.
Preparing for Senior Platform & SRE Interviews
Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.
Explore Interview Scenarios →