Skip to content
Tech Interview Prep
Technical interview guide

Kubernetes Operators & CRDs

Extending Kubernetes with custom resources and controllers to automate operational knowledge, not just deployment.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed
Relevant for
Platform Engineer

Scope: Kubernetes documentation and apiextensions.k8s.io/v1 behavior current 2026-08-31; verify feature-state notes against the target cluster version.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-3

Design spec, status, and conditions for a CRD.

Answer

First 90 seconds. Before designing fields I'd pin down two things: who is allowed to write each field, and what a client is allowed to gate on. My assumptions: a controller-based operator on a current Kubernetes (1.29+), one CRD, and at least one other system that reads this resource to decide whether to act. Given that, the split is: spec is the user's desired state, status is the controller's report of observed state, and nothing derivable lives in spec. Clients gate on status.observedGeneration plus conditions: never on a phase string or an Event stream.

Spec. Declarative intent only. Every field that is mutable after creation says so in the OpenAPI schema, and anything with a sensible default gets a default: in the structural schema so the stored object is unambiguous. Fields that must not change after creation are enforced with CEL (x-kubernetes-validations with oldSelf), not with a webhook: fewer moving parts, and the rule travels with the CRD. If a value is computed from other fields, it belongs in status, not spec.

Status. Enable the subresource (subresources: status: {}). That gives you two things: a spec write by a user with update on the resource can't clobber status, and RBAC can grant the controller status write without granting it spec write. Status carries observedGeneration (copied from metadata.generation), any stable external IDs the controller allocated, a summarized effective state, and conditions.

Conditions. Use metav1.Condition rather than a hand-rolled struct: it's the shape every Kubernetes tool already parses. Types are positive polarity (Ready, not NotReady), reason is a stable CamelCase token a machine can switch on, message is one actionable sentence for a human, and lastTransitionTime only moves when status flips.

YAML
status:
  observedGeneration: 7
  conditions:
    - type: Ready
      status: "True"
      observedGeneration: 7
      lastTransitionTime: "2024-05-02T10:14:03Z"
      reason: ReconcileSucceeded
      message: "3/3 replicas available"
    - type: Progressing
      status: "False"
      observedGeneration: 7
      lastTransitionTime: "2024-05-02T10:14:03Z"
      reason: ReconcileComplete
      message: "no pending changes"

Alternatives, and when to deviate.

OptionGood whenCost
Single phase enumStrictly linear lifecycle, one consumer, no orthogonal stateCan't express "serving but degraded"; every new state is a breaking enum change
ConditionsMultiple independent dimensions, several consumersVerbose; clients must know which type to gate on; no ordering between types
Events for stateAudit trail, debuggingBest-effort, TTL'd (~1h), aggregated: never gate on them
Status in the main resource (no subresource)Throwaway CRD, single writerAny spec update clobbers status; RBAC can't separate the two

I'd deviate to a phase only if the lifecycle is genuinely a state machine with one consumer, and even then I'd keep conditions alongside it.

Failure modes.

  • Stale status trusted. Client reads before the controller has reconciled. Detect by comparing status.observedGeneration to metadata.generation; if they differ, the status is from an older spec.
  • Status write conflicts. Concurrent writers hit resourceVersion conflicts. Use a merge or server-side apply patch, or retry on conflict: don't read-modify-write the whole object.
  • Hot-looping status writes. Writing on every reconcile churns every watcher. Only write when a field actually changes semantically.
  • Transient error blanks status. Keep the last known facts and set Ready=False, reason=ReconcileError instead of clearing the object; consumers lose their last good signal otherwise.
  • Secrets or unbounded text in status. Status is often readable by anyone with get on the resource. Never put credentials there, and cap message length: full detail goes to logs or Events.

What would change the decision. If no external system reads this resource, conditions are overkill and a phase plus Events is enough. If two controllers must write status, I'd split the CRD rather than share the subresource. And if the CRD is cluster-scoped and world-readable, I'd re-audit every status field for leakage before shipping.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design an idempotent reconciliation loop.

Answer

Assumptions. A Kubernetes controller (controller-runtime v0.17, Kubernetes 1.29) watching a CRD. The API server is the only source of truth; the process can be killed between any two instructions; every side effect is a declarative write to that same API server. Swap the last one for a card charge and this design is wrong: see the trade-offs.

Core. A reconcile is a function from observed state to a set of writes, run as often as it takes. Two properties make it idempotent: it reads before it writes, and every write is keyed by a name derived from the object, not from the attempt. It never assumes it saw every event, keeps no progress in memory, and never assumes exactly-once execution.

Go
// controller-runtime v0.17, Kubernetes 1.29
func (r *AppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	var app appv1.App
	if err := r.Get(ctx, req.NamespacedName, &app); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err) // gone: nothing to converge
	}

	if !app.DeletionTimestamp.IsZero() {
		if !controllerutil.ContainsFinalizer(&app, finalizerName) {
			return ctrl.Result{}, nil
		}
		if err := r.deleteExternalResources(ctx, &app); err != nil { // must tolerate NotFound
			return ctrl.Result{}, err
		}
		base := app.DeepCopy()
		controllerutil.RemoveFinalizer(&app, finalizerName)
		return ctrl.Result{}, r.Patch(ctx, &app, client.MergeFrom(base))
	}

	if !controllerutil.ContainsFinalizer(&app, finalizerName) {
		base := app.DeepCopy()
		controllerutil.AddFinalizer(&app, finalizerName)
		if err := r.Patch(ctx, &app, client.MergeFrom(base)); err != nil {
			return ctrl.Result{}, err
		}
		return ctrl.Result{}, nil // re-enter; metadata patches don't bump .metadata.generation
	}

	desired := r.desiredDeployment(&app) // stable name: app.Name + "-web"
	var cur appsv1.Deployment
	err := r.Get(ctx, client.ObjectKeyFromObject(desired), &cur)
	switch {
	case apierrors.IsNotFound(err):
		if err := controllerutil.SetControllerReference(&app, desired, r.Scheme); err != nil {
			return ctrl.Result{}, err
		}
		if err := r.Create(ctx, desired); err != nil && !apierrors.IsAlreadyExists(err) {
			return ctrl.Result{}, err // AlreadyExists: a previous pass won the race
		}
		cur = *desired
	case err != nil:
		return ctrl.Result{}, err
	default:
		if !deploymentMatches(&cur, desired) { // only the fields this controller owns
			base := cur.DeepCopy()
			cur.Spec = desired.Spec
			if err := r.Patch(ctx, &cur, client.MergeFrom(base)); err != nil {
				return ctrl.Result{}, err
			}
		}
	}

	ready, reason := deploymentReady(&cur) // re-observe after the write
	base := app.DeepCopy()
	app.Status.ObservedGeneration = app.Generation
	meta.SetStatusCondition(&app.Status.Conditions, metav1.Condition{
		Type: "Ready", Status: ready, Reason: reason, ObservedGeneration: app.Generation,
	})
	if !equality.Semantic.DeepEqual(base.Status, app.Status) {
		if err := r.Status().Patch(ctx, &app, client.MergeFrom(base)); err != nil {
			return ctrl.Result{}, err
		}
	}
	if !ready {
		return ctrl.Result{RequeueAfter: 10 * time.Second}, nil
	}
	return ctrl.Result{}, nil
}

Trace. App web at generation 3, no Deployment yet.

passtriggerwritesreturns
1create eventPATCH app (add finalizer){}
2pass 1's patchCREATE deployment, PATCH status (Ready=False/Progressing)RequeueAfter 10s
3pass 2's requeuenone{}

Pass 3 is the proof: spec matches, status already carries observedGeneration=3 and Ready=True, so DeepEqual is true and no request is sent. A pass fired by a Deployment status event also writes nothing.

Trade-offs.

alternativewins whencosts
exactly-once via a ledger or outboxthe side effect is not idempotent (charge a card, send an email)a durable dedup store, a two-phase commit, key lifecycle
leader-elected single writerthe side effect cannot tolerate concurrent attemptslease renewal, a new failure domain, slower failover
edge-triggered handlers onlyevent volume is huge and a dropped event is cheapcorrectness now depends on never dropping one

Deciding question: is the side effect idempotent by construction. A PUT keyed by a stable name? Then level-triggered reconcile is enough. If the process can die between the effect and the record of it, you need the ledger. One writer and no restart requirement: a retry loop with a dedup key is enough, and the loop above is overkill.

Failure modes.

  • 409 Conflict on a patch: return the error and let the default workqueue rate limiter retry (5 ms base, 1000 s max). Never retry in-process against the stale object.
  • Ambiguous create: the client times out after the server committed: the next pass Gets the object, and AlreadyExists is treated as success.
  • Finalizer leak: deleteExternalResources succeeded, the finalizer patch failed: the next pass re-runs the delete, so it must ignore NotFound.
  • Hot loop: a status field that changes every pass makes DeepEqual always false and requeues forever. Watch controller_runtime_reconcile_total against workqueue_depth.
  • Stale generation gate: gating all work on observedGeneration != generation skips readiness re-observation, since readiness changes without a generation bump. Symptom: Ready stuck False while pods report healthy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Manage child resources without field fights.

Answer

Assumptions I'd state up front: Kubernetes 1.29-era, a namespaced CRD Widget whose controller creates a Deployment and a Service per Widget, and other actors (users, an HPA, a mesh injector) also write to those children. If the children are exclusively yours and nobody else touches them, most of what follows is unnecessary and you should say so.

The answer: Ownership is two separate problems, who garbage-collects the child, and who owns each field. Solve them separately.

Garbage collection: set exactly one ownerReferences entry with controller: true and blockOwnerDeletion: true, which ctrl.SetControllerReference does for you. A namespaced owner must live in the same namespace as the child. A cross-namespace owner reference is not rejected at write time: the GC treats it as absent and deletes the child once all owners are verified absent. That is a silent data-loss bug, not an error you'll see in the reconcile.

Field ownership: use server-side apply (GA since 1.22) with a stable fieldManager such as widget-controller. The API server records which manager owns each field path in metadata.managedFields. When two managers write the same path, the second apply returns 409 naming the conflicting manager and path instead of silently clobbering. That is the whole mechanism: SSA converts a lost update into a visible error. A plain Update or JSON merge patch is last-writer-wins on the whole object, so you get flapping instead.

Go
// controller-runtime v0.17 / client-go v0.29
child := &appsv1.Deployment{
    TypeMeta:   metav1.TypeMeta{APIVersion: "apps/v1", Kind: "Deployment"},
    ObjectMeta: metav1.ObjectMeta{Name: w.Name + "-worker", Namespace: w.Namespace},
    Spec:       desiredSpec,
}
if err := ctrl.SetControllerReference(w, child, r.Scheme); err != nil {
    return err
}
err := r.Patch(ctx, child, client.Apply,
    client.FieldOwner("widget-controller"), client.ForceOwnership)

TypeMeta is required for apply. ForceOwnership takes the field from the other manager and records the takeover in managedFields; use it only for fields you genuinely own. Forcing .spec.replicas while an HPA also writes it means you win every reconcile and the HPA loses.

SymptomCauseDetection
Child deleted seconds after creationOwner ref namespace mismatch or stale UIDkubectl get deploy -o jsonpath='{.metadata.ownerReferences}'; GC events
409 on every reconcileAnother manager owns a field you applyError names manager and path; kubectl get --show-managed-fields -o yaml
Reconcile loop, no progressYour status write triggers your own watchReconcile count per object per minute; add GenerationChangedPredicate
Child never convergesController stuck mid-reconcilestatus.observedGeneration < metadata.generation for more than ~30s
Orphaned children after owner deleteGC disabled, or owner ref invalidChildren whose owner UID no longer exists

Adoption: before adopting an existing object with the name you want, compare an immutable identity. The parent UID in a label, plus the child's metadata.uid if you recorded it. If the label names a different parent UID, return an error rather than overwriting. Adoption is where two controllers can both claim one object and both set controller: true; the API server accepts that, and which owner the GC honours is not something to rely on.

Trade-offs: SSA is right when several actors write disjoint fields of the same object. Narrow JSON merge patches are right when you own one field and must not touch anything else, but they carry no ownership record, so a conflict stays invisible. A CRD-per-child removes the problem entirely, nobody else writes your CR, at the cost of an extra API object and its own schema. If the child is a CRD without listType markers, SSA treats lists as atomic, so any list field becomes a fight; keep it in a separate object or patch it narrowly.

Deletion: foreground deletion blocks the owner until children are gone via the foregroundDeletion finalizer, background returns immediately and the GC deletes children asynchronously, and --cascade=orphan strips owner references. Choose foreground when a child holds an external resource you must release first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Handle deletion and recreation with the same resource name.

Answer

Assumptions to state up front: you are writing an operator whose custom resource name derives the name of something outside the cluster (load balancer, DNS record, IAM role, bucket, queue), the provider deletes asynchronously, and the cloud account may be shared with other clusters.

The core answer. Name is a lookup key; UID is identity. You cannot recreate the CR while the old one is alive: until its finalizers are removed, a same-name create is rejected with 409 AlreadyExists. So the window you have to defend is everything the old CR left behind. Three rules follow.

  1. Tag every external object with the owning CR's metadata.uid, a cluster identity, and the purpose. Adoption requires a tag match; a mismatch is reported as a status condition, never adopted and never deleted.
  2. The deletion finalizer blocks until the provider confirms the object is gone, not merely until the delete call is accepted.
  3. Every asynchronous provider completion carries the requesting UID and compares it to the live object's UID before it writes status.

In-cluster children need none of this: ownerReferences carry uid and the garbage collector honours it. Two exceptions. A controller that adopts by label selector must still check ownerReferences[].uid. And cross-namespace owner references are ignored by the GC, so those bindings are yours to tag and verify yourself.

strategyexternal namename reuse after recreatecost
deterministic name + uid tagw1-lbcreate fails AlreadyExists until the old object drains; reconcile waits and reports a conflicthuman-legible names, one code path, but you need the wait path and must never adopt an untagged object
deterministic name + short uid hashw1-7f3a91c4-lbno collision, everopaque names; you must list by tag to find and collect orphans after a crash
name only, no tagsw1-lbadopts or deletes the previous object, or a peer cluster'sacceptable only for one cluster in one account with no other writers

ELBv2 names cap at 32 characters and must be unique per region per account, which is why the uid goes in a tag rather than the name: a uid is 36 characters by itself.

Go
// controller-runtime v0.17, client-go v0.29
type pending struct {
	key  types.NamespacedName // ns/name of the CR
	uid  types.UID            // the CR that asked for this create
	opID string               // provider operation id
}

func (r *Reconciler) completeCreate(ctx context.Context, p pending, arn string) error {
	var cr v1alpha1.Widget
	switch err := r.Get(ctx, p.key, &cr); {
	case apierrors.IsNotFound(err):
		return r.deleteExternal(ctx, arn, p.uid) // CR gone: nobody owns this
	case err != nil:
		return err
	case cr.UID != p.uid:
		return r.deleteExternal(ctx, arn, p.uid) // same name, different object
	}
	return r.setStatus(ctx, &cr, arn)
}

Trace it. At t0 Widget ns/w1 has uid U1 and reconcile issues CreateLoadBalancer, recording pending{ns/w1, U1, op-1}. At t1 the user deletes w1; the finalizer finds no load balancer yet recorded and removes itself, so w1 is gone at t2. At t3 the user creates ns/w1 again with uid U2, and the new reconcile's create comes back as a duplicate name while op-1 is still in flight, so it requeues and reports a conflict condition. At t4 op-1 completes: completeCreate reads ns/w1, sees U2 != U1, and deletes the object it created. Without that check it would write U1's ARN into U2's status, and U2 would later delete a load balancer it never owned.

Failure modes and how each is detected. Shared-account adoption: another cluster (say staging) manages a CR also called w1 in the same account; list by your cluster tag at startup and periodically, and alert when you find a resource with your naming pattern and someone else's cluster identity. Deleting it by name is how you take down another team's environment, so report instead. Stale status write: test with a fake provider that deletes and recreates the CR between the create call and the callback, then assert the new CR's status is empty and its uid appears in no provider tag. Queue key collapse: workqueue keys are ns/name, so a delete plus add of the same name coalesces into one reconcile, which is fine as long as you re-Get inside reconcile and never pass an object pointer from an event handler into an async goroutine; a status update built from a pre-delete snapshot then fails with 409 Conflict on resourceVersion, which is loud rather than silent. Early finalizer exit: recreate the CR immediately after the delete is accepted, and assert the second reconcile cannot see the old tagged object.

What would change this: if the provider's delete is synchronous and its create accepts a client idempotency token, tag checks shrink to a startup orphan sweep. If each tenant gets its own account, the cluster tag is dead weight. And when the external name is globally unique across accounts (S3 buckets), stop deriving it from the CR name entirely and use a random suffix, because that name is not yours to reuse.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Implement safe finalizer cleanup.

Answer

A finalizer is a lease on deletion, not cleanup logic. It is correct only if you add it before the first external side effect and remove it only after a fresh read proves nothing you created still exists. Deciding from a cached status you wrote ten seconds ago is how these leak.

Ordering. The dangerous gap sits between creating the external resource and recording that you did. Persist the finalizer first:

Go
// <dns-subdomain>/<name>; the name segment is capped at 63 characters
const finalizer = "apps.example.com/external-lb-cleanup"

if app.DeletionTimestamp.IsZero() {
    if !controllerutil.ContainsFinalizer(&app, finalizer) {
        patch := client.MergeFrom(app.DeepCopy())
        controllerutil.AddFinalizer(&app, finalizer)
        if err := r.Patch(ctx, &app, patch); err != nil {
            return ctrl.Result{}, err
        }
        return ctrl.Result{}, nil // persisted before any cloud call
    }
    return r.provision(ctx, &app)
}
return r.cleanup(ctx, &app)

A crash after that patch leaves a finalizer with nothing to delete, which is a no-op. A crash after the cloud create but before the patch would leak the load balancer, and this order makes that case unreachable. The price is dead no-op reconciles, which are free. Once deletionTimestamp is set, stop reconciling toward spec: provisioning that keeps running during termination is how you race your own cleanup.

Identity. metadata.name is reusable, metadata.uid is not. Delete web and recreate it, and two distinct objects have shared a name. Key external resources on the name and the terminating old object's cleanup will delete the new one's load balancer, which is the classic data-loss bug in this area. Tag the external resource with the UID at creation, match on the tag at delete, and ignore any watch event carrying a UID you never recorded.

Idempotency. A retry can repeat a side effect that already happened, because a 500 can follow a committed delete. Two rules cover most providers: treat NotFound as success, since the second call is the normal case, and pass the provider's idempotency token on the create side where it exists so a retried create cannot duplicate. Conditions then exist for humans, not for the decision.

Trace, as the reconciler runs it:

  • t=0s: the API server sets deletionTimestamp. A lookup by UID tag finds lb-0a1b; DeleteLoadBalancer returns 500, though the delete committed.
  • t=0s: write CleanupComplete=False, reason=ExternalResourceRemaining, return the error. controller-runtime's default exponential limiter starts at 5ms, doubles, caps at 1000s, behind a 10 qps / 100 burst bucket. Five milliseconds is useless against a cloud API, so reserve errors for real failures and poll with RequeueAfter: 5*time.Second.
  • t=10s: the tag lookup still returns lb-0a1b, because provider tag search lags the delete. Delete again; this time 404, treated as success.
  • t=15s: a fresh lookup returns nothing. RemoveFinalizer, then Update. With the last finalizer gone, the API server deletes the object from etcd.

The contract is external: no resource tagged with this UID exists on a read that bypasses your cache, and your Kubernetes children are gone. Ordering matters there too, because background propagation removes the owner's etcd record while dependents are still being collected. If order matters, use --cascade=foreground or delete the children yourself and wait.

Failure modes worth an alert:

  • Two controllers each waiting on the other. Alert on deletionTimestamp age past 15 minutes, per object. A stuck finalizer holds the whole namespace in Terminating, which also blocks the namespace name from being reused.
  • The controller was uninstalled and nobody owns the finalizer. Same age alert; the runbook reads the list and removes only yours: kubectl patch app web --type=merge -p '{"metadata":{"finalizers":["other.example.com/thing"]}}'. Merge patch replaces the array wholesale, so re-read immediately before patching.
  • A leak with no recorded handle. Sweep the provider for resources tagged with this cluster and diff against live UIDs.

Abandonment is a separate authority decision and only for cost. It is defensible when the provider is unreachable, or the resource is confirmed gone out of band and the orphan bills but does nothing else: one orphaned load balancer at $0.03/hour is 8760 * $0.03 = $263/year (illustrative). It is not defensible when the finalizer is what stops data loss or exposure. Record who decided and which UIDs were released.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Handle external resource creation when the response is lost.

Answer

What I'd say first

"Lost response" means the create call may have landed and we can't tell: the HTTP client timed out, or the controller died between the call returning and the status write. You can't get exactly-once across two systems that don't share a transaction, so the goal is effectively-once: put a key on the create request that is stable across retries, and make the retry path able to discover and adopt a resource that already exists.

Assumptions: a Kubernetes operator reconciling a CR, talking to a cloud API. metadata.uid is a UUID assigned at creation and never reused; metadata.name is reusable in a namespace after delete. That difference decides the key.

The mechanism

Derive the key from metadata.uid plus the purpose: sha256(uid + "/bucket"), hex-encoded. UID, not name: key on name and a CR deleted and recreated with the same name will adopt the previous CR's resource.

Add the finalizer before this runs, so a crash can't leave an un-deletable CR with a live resource behind it.

Go
// Go 1.21, controller-runtime v0.17
func (r *Reconciler) ensureBucket(ctx context.Context, cr *v1alpha1.Bucket) error {
    if cr.Status.ProviderID != "" {
        return nil // already bound
    }
    key := idemKey(cr.UID, "bucket") // sha256 hex of uid + purpose

    if id, ok, err := r.provider.FindByTag(ctx, "op.example.com/idem-key", key); err != nil {
        return err
    } else if ok {
        return r.bind(ctx, cr, id) // adopt
    }

    id, err := r.provider.Create(ctx, CreateReq{
        Name:    "b-" + string(cr.UID)[:8],
        IdemKey: key,
    })
    if err != nil {
        return err // requeue; the next pass re-searches
    }
    return r.bind(ctx, cr, id)
}

bind writes status.providerID and status.observedGeneration = cr.Generation.

Crash points, and what the next reconcile sees:

crash pointstate on next passaction
before Createno resource with the keycreate
after Create, before bindresource with the key, status.providerID emptyadopt, write providerID
after bindstatus.providerID setno-op

The only way to get a duplicate is a provider that ignores the key and a stale search.

Trade-offs

Search-before-create is the wrong tool when the provider has no list/filter API, or when its list is eventually consistent. EC2 is the classic case: DescribeInstances filtered on a tag can lag RunInstances by seconds, so a search right after a timed-out create returns empty and you create a second instance. There you lean on the provider's own token (ClientToken on RunInstances, which AWS documents as honored for 24 hours) and treat a duplicate-name error as success.

Azure is a different shape: ARM's PUT is idempotent on the resource ID, so a lost response just means re-PUT the same body. GCP compute insert calls take a requestId with similar bounded-window semantics. If a provider has neither a key nor a list API, make the name deterministic (b-<uid-prefix>) and treat 409 Conflict / AlreadyExists as success.

Failure modes

  • Duplicates: list by key, find two. Delete neither: you don't know which one holds data. Set a condition DuplicateDetected carrying both IDs, stop the destructive path, and let a human or a policy decide.
  • Wrong adoption: before adopting, check immutable attributes. Account, region, creation time, owner tag. A resource matching the key but sitting in another account is not yours.
  • Finalizer leak: finalizer added, create never happened, delete blocks forever. If status.providerID is empty and the search finds nothing, remove the finalizer.
  • Tag eventual consistency: the key is the backstop, not the search.

Testing

Use a fake provider that applies the effect and then returns a timeout. Crash the reconciler at each of the three points above and assert the next reconcile converges to exactly one resource. Then have the fake ignore the key and assert the duplicate path fires the condition instead of deleting anything.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Handle drift between spec and an external system.

Answer

Clarify first. Two things decide the design: which side owns each field, and what a wrong write costs. If the external system is a cloud provider that assigns defaults, most apparent drift is not drift at all: it is late initialization. If the controller owns a field and the external system also writes it, you have a fight, not drift.

Assumptions I'd state: the spec is declarative and versioned; the external system has read and write APIs with different rate limits; reconciliation runs on a timer, not on every event; and some resources are irreversible to recreate (databases, DNS zones, IAM roles with attached policies).

The answer. Classify every field into three buckets and publish that contract as code, not prose:

bucketwho writesreconcile action
controller-authoritativespecwrite back, idempotent, rate-limited
externally-authoritativeexternal systemread into status; never write
observe-onlynobodyreport and alert, no action

Concretely: in Crossplane, spec.managementPolicies: [Observe] makes a managed resource read-only. The observe-only bucket expressed in the API. In Terraform, lifecycle { ignore_changes = [tags["LastScanned"]] } is the externally-authoritative bucket, and prevent_destroy = true protects the irreversible ones. In Argo CD, ignoreDifferences on /spec/replicas is how you stop the GitOps controller fighting an HPA that owns replica count.

Reconcile loop. Read external state by a stable binding: resource ID, not name, because names get reused. Normalize before comparing: case, ordering, provider-assigned defaults, timestamps. Compare semantic values, not serialized bytes. Then act per bucket. For controller-owned drift, issue idempotent writes under a rate limit: client-go's default client QPS is 5 with burst 10, and controller-runtime's default SyncPeriod is 10 hours. Both are too slow for a hot fix and too fast for a full-estate refresh, so tune per resource class. A full refresh is expensive: Terraform's default plan reads every managed resource, so a few thousand resources means a few thousand read calls and the usual cause of RequestLimitExceeded. Use terraform plan -refresh-only when you want to record drift without changing infrastructure.

Trace one cycle. Spec says replicas: 3, tags.owner: platform. The external read returns replicas: 7 (HPA scaled), tags.owner: platform, tags.lastScanned: <timestamp> (provider-added). Compare: replicas is externally-authoritative, so write it to status and take no action; tags.owner matches, no action; tags.lastScanned is not in the spec, so it is late-init and ignored. Net writes: zero. Most cycles should write nothing.

Failure modes and detection.

  • Oscillation: two writers flip the same field. Detect by counting updates to the same object per hour; two controllers writing the same path is the signature. Fix by assigning ownership, not by shortening the loop.
  • Late initialization mistaken for drift: the provider fills in a default (an ARN, a default egress rule) and the controller reverts it forever. Detect by diffing the first observed state against the spec; a field that was never in the spec is late-init. Crossplane's LateInitialize policy and Terraform's provider normalization exist for this.
  • Destructive repair: a plan showing -/+ on a database because one field changed. Gate that behind approval; never let an automated loop replace stateful resources.
  • Throttling: refresh storms. Detect via 429 and RequestLimitExceeded rates plus reconcile queue depth.

Trade-off. Aggressive auto-heal converges fast and can destroy data; observe-only is safe and lets drift accumulate. The right split is per field, and that split is the contract. Record actor and evidence where the external system exposes it (CloudTrail, audit logs) so a human can separate a legitimate external change from a rogue one. Make pause explicit: a maintenance window that suppresses reconciliation must be a recorded, expiring state, not a silently disabled loop. Otherwise drift accumulates invisibly and the next plan is a surprise. Monitor drift age and recurrence count, not just drift presence; a field that drifts daily is a design bug, not an incident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Classify reconciliation errors and retries.

Answer

What a strong candidate says first

The classification only matters because it picks the retry policy. In a controller-runtime reconciler there are three levers (return nil, return an error, or return a Result with RequeueAfter) and each drives the queue differently. So classify by what the queue should do next, not by error type.

BucketExampleReturnQueue effect
Settledspec applied, status currentResult{}, nilForget; no requeue
Not-yet-readyDeployment rollout at 3/5Result{RequeueAfter: 30s}, nilForget + AddAfter: fixed delay, resets failure count
Conflict409 on Update, stale resourceVersionResult{}, errAddRateLimited: refetch next pass
ThrottledAPI server 429, provider Retry-AfterResult{RequeueAfter: retryAfter}, nilfixed delay, no backoff growth
Transient5xx, connection reset, webhook timeoutResult{}, errAddRateLimited: exponential backoff
Terminalinvalid spec, immutable field changeResult{}, nil + condition/eventno requeue until generation changes
Needs humanmissing Secret, quota exceededResult{}, nil + condition/eventno requeue; alert
Go
switch {
case err == nil && ready(&app):
    return ctrl.Result{}, nil                                // settled
case err == nil:
    return ctrl.Result{RequeueAfter: 30 * time.Second}, nil  // not-yet-ready
case apierrors.IsConflict(err):
    return ctrl.Result{}, err                                // refetch next pass
case isThrottled(err):
    return ctrl.Result{RequeueAfter: retryAfter(err)}, nil
case isTerminal(err):
    setCondition(&app, "InvalidSpec", err)
    return ctrl.Result{}, nil                                // no requeue
default:
    return ctrl.Result{}, err                                // transient -> backoff
}

Why it behaves that way

controller-runtime's queue distinguishes the three returns. An error calls AddRateLimited, running the item through the default rate limiter: ItemExponentialFailureRateLimiter(5ms, 1000s) maxed with a BucketRateLimiter(10 qps, burst 100). RequeueAfter calls Forget then AddAfter: it clears the failure count and schedules a fixed delay. Requeue: true also goes through AddRateLimited.

That distinction is the point of the not-yet-ready bucket: a rollout that takes ten minutes must not accumulate ten minutes of exponential backoff, so you poll with RequeueAfter and keep the failure counter at zero. Reserve error returns for things that are actually wrong.

Trade-offs

  • RequeueAfter vs error: polling a slow dependency costs one API call per interval per object; returning an error instead makes the interval grow to 1000 s and the object looks stuck. Use RequeueAfter when "not done yet" is normal.
  • Don't retry terminal errors. An invalid spec retried forever burns API QPS and hides the real problem behind a backoff that never surfaces. Set Ready=False with reason InvalidSpec, emit an event, return nil.
  • Conflicts are cheap and self-resolving; letting them ride the backoff (5 ms first retry) is fine. Don't hand-roll a conflict loop.
  • MaxConcurrentReconciles defaults to 1. Raising it helps throughput but multiplies API load; pair it with the bucket limiter.

Failure modes and how you see them

  • Hot loop: a reconciler returning an error on a permanent condition. Symptom: workqueue_adds_total climbing while workqueue_depth sits near zero, rest_client_requests_total spiking.
  • Permanent stall: a terminal error swallowed as transient. Symptom: observedGeneration lags metadata.generation indefinitely, no events. Alert when the gap persists past N minutes.
  • Backoff starvation: one object pinned at the 1000 s cap. Symptom: workqueue_retries_total high for a single key; ~17 min between attempts.
  • Thundering herd: a dependency recovers and every object requeues at once. Symptom: API QPS spike. Mitigate with jitter and the bucket limiter.

Worked trace: backoff for a transient error

Failure 1 → 5 ms, 2 → 10 ms, 3 → 20 ms … delay is 5ms × 2^(k-1). It hits the 1000 s cap at failure 19 (5ms × 2^18 ≈ 1310 s, clamped). So a genuinely transient error is retried ~19 times over roughly 40 minutes before settling at one attempt per ~17 minutes. If the object is still failing after that, it is not transient: it is terminal or needs a human, and the classification should have caught it earlier.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design operator leader election and failover.

Answer

Assumptions I'd state up front: a Kubernetes operator built on controller-runtime, several replicas of one Deployment, one API server, and at least some reconciles that are not safe to run twice at once. If every reconcile is safe concurrently, I'd skip leader election and shard work across replicas instead: a global singleton is a cost, not a default.

The answer

Use the Lease-based election already in client-go and controller-runtime. Don't write your own lock. Set the three timings explicitly rather than inheriting them, and keep the invariant RetryPeriod < RenewDeadline < LeaseDuration.

settingcontroller-runtime fielddefaultwhat I'd ship
lease durationLeaseDuration15s15s
renew deadlineRenewDeadline10s10s
retry periodRetryPeriod2s2s
release on cancelLeaderElectionReleaseOnCancelfalsetrue
lock typeLeaderElectionResourceLockleasesleases (the configmaps lock is deprecated)
lock nameLeaderElectionID—unique per operator, e.g. ingress-operator.example.com
Go
// checked against controller-runtime v0.17
mgr, err := ctrl.NewManager(cfg, ctrl.Options{
    LeaderElection:                true,
    LeaderElectionID:              "ingress-operator.example.com",
    LeaderElectionNamespace:       "operators", // defaults to the pod's namespace in-cluster
    LeaderElectionReleaseOnCancel: true,
    LeaseDuration:                 ptr.To(15 * time.Second),
    RenewDeadline:                 ptr.To(10 * time.Second),
    RetryPeriod:                   ptr.To(2 * time.Second),
})

RBAC needs get, create, update on leases in that namespace.

Failover arithmetic. A leader that cannot renew for 10s gives up. A follower may claim the lease once its renewTime is 15s old, and it retries every 2s. So a hard kill costs roughly 15–17s with no leader. With ReleaseOnCancel: true and a clean SIGTERM, the lease is released and failover is sub-second: that flag is the single biggest win here.

What the lease does not give you

The lease is advisory. A leader partitioned from the API server but still able to reach your cloud provider keeps acting, and the new leader acts too. So:

  • Every API write carries resourceVersion; a stale write gets 409 Conflict and is retried.
  • Irreversible external actions carry a fencing token, the lease's resourceVersion or a monotonic counter, and the provider rejects stale tokens.
  • Creates use deterministic names and treat AlreadyExists as success.

Startup: the manager waits for cache sync before controllers run, and election happens before that. On losing leadership the manager cancels the context and stops controllers, but an in-flight reconcile can still finish: that is why the three rules above exist.

Failure modes and how I'd detect them

  • SIGKILL. No release, ~15s gap. Watch the leader_election_master_status gauge: it should be 1 on exactly one pod.
  • Partition from the API server. Old leader stops renewing, new leader takes over at 15s, old leader may still touch external systems. Fencing tokens are the only real fix.
  • Clock skew. The leader stamps renewTime from its own clock and followers compare against theirs. Keep NTP within a few hundred ms; skew past RenewDeadline causes flapping.
  • Slow shutdown. Set terminationGracePeriodSeconds above the reconcile budget; ReleaseOnCancel only helps if the process actually exits.

Test by kill -9-ing the leader, dropping traffic to the API server with iptables on the leader, stopping the API server entirely, skewing the clock, and sending SIGTERM mid-reconcile.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Scale an operator to many custom resources.

Answer

Core answer (first 90 seconds)

Assume one controller binary, ~50k custom resources across ~3k namespaces, and each reconcile calls an external provider with its own quota. The goal is to keep the API server and the provider alive while still converging.

Answer: one shared informer per GVK per process, a filtered event stream, a workqueue keyed by namespace/name, and bounded concurrency. Make a single replica cheap before you add replicas.

Why shared informers scale

A shared informer runs one LIST then one WATCH per GVK per process, not per object. The reflector writes into a DeltaFIFO, the informer drains it into a thread-safe Indexer (the cache), and every registered handler reads that same cache. So 50k objects cost one watch connection and one in-memory store, and reconcile handlers do O(1) map lookups instead of GETs. That is the whole scaling story: watch, don't poll; read the cache, don't call the API.

Predicates

Without predicates, every status write, heartbeat annotation, or resync re-enqueues the object. GenerationChangedPredicate drops updates where only status changed: spec changes bump metadata.generation, status writes don't. Add LabelChangedPredicate or AnnotationChangedPredicate only for fields you actually watch. This is the difference between 50k reconciles/hour and 50k reconciles/second.

Workqueue

Keys are namespace/name strings, so duplicate events for the same object collapse into one queue entry: dedup is free. The default rate limiter is exponential from 5 ms to 1000 s plus a 10 qps / 100 burst token bucket; keep it, and add a per-provider limiter on top so you don't blow the provider's quota. MaxConcurrentReconciles defaults to 1; raise it to roughly the number of independent provider calls you can have in flight, not to the object count.

Client-side limits

rest.Config defaults are QPS 5 / Burst 10 in client-go; controller-runtime raises them to 20/30. Don't set them to 1000: that just moves the overload to the API server. Use paginated LISTs (limit=500, follow continue) for any startup full-list, and never full-list inside reconcile. Resync defaults to 0 in raw client-go and 10 hours in controller-runtime's SyncPeriod; a short resync is a self-inflicted herd.

Sharding vs scoped caches vs vertical

  • Scoped caches (namespace or label selector) first: cheapest, no coordination, but each replica still watches everything matching its selector.
  • Vertical: more MaxConcurrentReconciles and a bigger cache. Fine until one process's memory or GC dominates.
  • Sharding: consistent hash on object UID across replicas, each replica filtering in the predicate or watching a selector. Needs ownership and failover: leader election via a coordination.k8s.io/v1 Lease (15 s lease, 10 s renew deadline, 2 s retry). Only shard when one replica can't keep up, because you now own rebalancing and split-brain.

Failure modes

  • Watch closed or 410 Gone: the reflector relists. Symptom: cache-lag spike and a burst of reconciles. Detect via reflector_list_duration_seconds and watch error counters.
  • Thundering herd after an outage: every object re-enqueued at once. Detect via workqueue depth; mitigate with the rate limiter and per-provider concurrency cap.
  • Provider saturation: 429s. Detect via provider error rate; back off per provider, not globally.
  • Stale cache: reconcile reads an object the cache hasn't caught up to. Detect by comparing resourceVersion or tracking cache lag.

Metrics: workqueue depth and oldest-item age, reconcile duration and error rate, API request rate and 429s, cache lag, stale generation count, provider saturation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design CRD validation and defaulting.

Answer

Assumptions: apiextensions.k8s.io/v1 (structural schemas mandatory since 1.16), cluster on 1.29+ so CEL validation rules are GA, and the CRD already holds thousands of objects I can't rewrite in one pass.

Core answer. Put everything declarative in the structural schema, use CEL for relationships between fields of the same object, and keep a validating webhook out of the write path unless the rule genuinely needs data the API server doesn't have. Default a field only where "absent" and the default value are already equivalent to every consumer.

Why the split works. The API server validates on write only: create and update. It never re-validates objects already in etcd on read. Defaulting and pruning, by contrast, run on read from etcd as well as on write. That asymmetry drives the design: adding a default: retrofits existing objects for free, adding a required: does not.

YAML
# apiextensions.k8s.io/v1, checked against Kubernetes 1.29
properties:
  spec:
    type: object
    required: [replicas, mode]
    properties:
      replicas: {type: integer, minimum: 1, maximum: 100, default: 3}
      mode: {type: string, enum: [Active, Passive], default: Passive}
      endpoints:
        type: array
        x-kubernetes-list-type: map
        x-kubernetes-list-map-keys: [name]
        items:
          type: object
          required: [name, port]
          properties:
            name: {type: string}
            port: {type: integer, minimum: 1, maximum: 65535}
    x-kubernetes-validations:
      - rule: "self.mode == 'Passive' || (has(self.endpoints) && size(self.endpoints) >= 2)"
        message: "Active mode requires at least two endpoints"
      - rule: "self.replicas >= oldSelf.replicas"
        message: "replicas may not be decreased"

The second rule references oldSelf, which makes it a transition rule: the API server evaluates it only on update, so it can't fire on create. x-kubernetes-list-type: map with x-kubernetes-list-map-keys gives merge semantics, so two controllers editing different endpoints don't clobber each other; atomic would replace the whole list.

Choosing the mechanism.

mechanismevaluated onsees other objectscost
structural schemacreate, updatenoin-process
CEL rulecreate, updateno: self/oldSelf onlyin-process; cost estimated at CRD write
validating webhookcreate, updateyes, can call the APInetwork hop + availability dependency

A webhook with the default timeoutSeconds: 10 and failurePolicy: Fail can add up to 10 s to every write and blocks all writes to the CRD when the service is down. Schema and CEL run inside the API server process with no round trip. Reach for a webhook only for cross-object rules (quota, uniqueness against another resource), and then set sideEffects: None, a short timeout, and objectSelector to narrow what it sees.

Failure modes.

Tightening a rule on a populated CRD. Reads keep working because nothing re-validates on read; the breakage lands on the first controller that does read-modify-write. Detect it before shipping by running kubectl apply --dry-run=server over the stored objects and counting failures: server dry-run does run validation. Cost of skipping this: a controller that can't update its own object wedges, and you're doing a data migration mid-incident. Ratchet instead: optionalOldSelf: true (1.29+) skips the rule when the old object is already invalid, so existing bad objects can still be edited while new ones are held to the rule.

Defaulting versus pruning. A default inside a subtree that gets pruned never applies, and a default added later silently changes what "absent" meant. If a controller branches on absent versus ""/0, retrofitting a default flips that branch on read. Test with an object stored before the default existed.

Silent typos. Unknown fields are pruned by default, and fieldValidation defaults to Warn since 1.27, so a misspelled field is dropped with a warning rather than rejected. Use fieldValidation=Strict in CI.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design admission for an operator API.

Answer

Core answer (first 90 seconds)

Assume the operator ships CRDs, so admission runs inside the API server's request path on every create/update of those types. The operator's controller is not in that path: it reconciles afterwards. So the design question is: which checks can be answered from the object alone, which need the cluster, and which need something outside it. Push as much as possible into the CRD schema and CEL, then ValidatingAdmissionPolicy, and use a webhook only for what neither can do.

Layer 1: CRD schema. default: in the OpenAPI schema fills fields before validation, so the controller never sees a zero value it has to guess at. x-kubernetes-validations CEL rules cover object-local invariants: self.replicas <= self.maxReplicas, immutability via oldSelf. These run in-process, have no network hop and no failurePolicy, and version with the CRD. Watch the CEL cost budget: a rule that iterates a large list is rejected at CRD apply time.

Layer 2: ValidatingAdmissionPolicy (GA since 1.30). Use it when the rule needs cluster-scoped parameters via paramKind, or must apply across several resources, but still needs no live lookup. validationActions: [Deny] with failurePolicy: Fail on the binding. Same in-process cost profile, no availability surface.

Layer 3: webhook. Only for what CEL cannot do: a live lookup of an object not in the request, an external registry call, or mutation. Scope it tightly:

YAML
rules:
- apiGroups: ["db.example.com"]
  apiVersions: ["v1"]
  resources: ["clusters"]
  operations: ["CREATE","UPDATE"]
  scope: Namespaced
failurePolicy: Fail
matchPolicy: Equivalent
sideEffects: None
timeoutSeconds: 3
admissionReviewVersions: ["v1"]

timeoutSeconds: 3, not the 10 default: the webhook is a synchronous hop and the API server holds the request goroutine for the whole timeout. sideEffects: None is what lets kubectl --dry-run=server reach the webhook at all: Unknown silently skips it. matchPolicy: Equivalent so a request through an older served version still hits it. For mutation, reinvocationPolicy: IfNeeded and idempotent logic: the webhook can be called twice on one object if another mutating webhook runs after it. Never provision external resources in a mutating webhook: dry-run requests would create them.

Failure modes

  • Webhook down with failurePolicy: Fail → every create/update of that CRD returns 500. Detect with apiserver_admission_webhook_rejection_count; alert on it. Cost: the operator's API is down while the operator itself is healthy.
  • Webhook slow → request goroutines pile up and p99 degrades for the whole API server, not just that CRD. Detect with apiserver_admission_webhook_admission_duration_seconds p99 against your 3s timeout.
  • failurePolicy: Ignore → invalid objects persist; the controller must reject them asynchronously and you get a CR that exists but never reconciles. Detect with a controller-side validation-failure counter.
  • Reinvocation loop: two mutating webhooks each adding a default and each triggering the other. The API server caps reinvocations and the object lands half-mutated. Detect by diffing the object before/after in the audit log.

Trade-offs

failurePolicy: Fail when the webhook enforces an invariant the controller cannot repair: tenancy, quota. Ignore when the webhook is advisory or the controller converges the object into validity anyway, e.g. a defaulting webhook whose output the controller would set on first reconcile. The flip point: can the system converge without this decision? Yes → Ignore. Unrecoverable bad object → Fail.

VAP versus webhook: VAP when the rule is expressible in CEL over the object plus params. It has no availability surface. Webhook when you need a live lookup or mutation. Using a webhook for something CEL can express buys a network hop and an outage mode for nothing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Version a CRD from v1alpha1 to v1.

Answer

Two things decide the plan: does v1 change the schema, or only the version string, and are any clients still pinned to v1alpha1? If the schemas are identical apart from apiVersion, set conversion.strategy: None and skip the webhook entirely. If fields were renamed, retyped or restructured, you need a conversion webhook. Assume the harder case, with clients still on v1alpha1.

A CRD serves a list of versions and exactly one is storage: true: that is the only version written to etcd. Every read or write for a non-storage version is converted. With strategy: None the apiserver only rewrites the apiVersion field, so all versions must share one schema. With strategy: Webhook the apiserver POSTs a ConversionReview to your service and uses the objects it returns. That webhook sits on the request path for every non-storage-version call, so it must be highly available, and it must not itself be an object of the CRD it converts: otherwise you deadlock bringing it up.

YAML
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: widgets.example.com
spec:
  group: example.com
  names: {kind: Widget, plural: widgets, singular: widget}
  scope: Namespaced
  conversion:
    strategy: Webhook
    webhook:
      conversionReviewVersions: ["v1"]
      clientConfig:
        service: {name: widget-conversion, namespace: example-system, path: /convert}
        caBundle: <base64 CA>
  versions:
    - name: v1alpha1
      served: true
      storage: false
      deprecated: true
      deprecationWarning: "example.com/v1alpha1 Widget is deprecated; use v1"
      schema: {openAPIV3Schema: {type: object, ...}}
    - name: v1
      served: true
      storage: true
      schema: {openAPIV3Schema: {type: object, ...}}

Add v1 as served, keep v1alpha1 served, then flip storage to v1. New writes land in v1; existing objects stay in v1alpha1 in etcd. status.storedVersions records every version ever persisted, and the apiserver rejects removing a version from spec.versions while it is still listed there. The trace:

# after flipping storage to v1, before migration
status.storedVersions: [v1alpha1, v1]   # v1alpha1 objects still in etcd, v1 now taking writes

# after every object is rewritten under v1
status.storedVersions: [v1]             # only now can v1alpha1 be dropped

Rewrite with kube-storage-version-migrator (a StorageVersionMigration for the group/resource) or a read-and-replace loop. The migrator removes a version from storedVersions only after confirming no object remains stored under it.

failurehow it shows up
Webhook downreads/writes of v1alpha1 return 500; v1 (storage) still works. apiserver_request_total{code="500"} for the group, plus webhook error/latency metrics.
Webhook depends on the CRDconversion never comes up; the webhook Deployment can't be created. Caught at deploy time.
Clients pinned to v1alpha1after removal their calls 404. Check audit logs and apiserver_request_total by version before removing.
storedVersions not clearedCRD update rejected with a validation error naming the version.
Conversion drops fieldsround-trip test (v1alpha1 → v1 → v1alpha1) fails; otherwise the loss is silent.
etcd restore from before migrationstoredVersions reverts and objects are v1alpha1 again; if the webhook is gone they are unreadable as v1.

Deprecate with deprecated: true and a deprecationWarning, which the apiserver returns in a Warning header so clients see it. Watch telemetry until v1alpha1 traffic is zero, then remove it from spec.versions and drop the webhook if no other version needs it. Keep the webhook until the last non-storage version is gone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Recover from a broken conversion webhook.

Answer

Assumptions: a CRD widgets.example.com with v1 (storage) and v1beta1, spec.conversion.strategy: Webhook pointing at a Service in namespace webhooks. Cluster-scoped resource.

The 90-second answer. The storage version still serves; only the non-storage versions are broken. Confirm that, then restore the webhook, or roll it back, and leave stored data alone until conversion works again. Don't flip the conversion strategy or drop versions from the CRD to "unblock" yourself; both can silently lose fields.

Why it breaks this way. The API server reads and writes objects in the storage version straight from etcd. Any request that names a different version has to be converted, and with strategy: Webhook that conversion is an HTTP call to your service. Webhook down → every v1beta1 read and write fails with a conversion error, while v1 keeps working. status.storedVersions lists the versions actually present in etcd; the API server rejects removing a version from spec.versions while it is still listed there.

Confirm the blast radius.

kubectl get crd widgets.example.com -o jsonpath=\
'{.spec.conversion.strategy}{"\n"}{.status.storedVersions}{"\n"}{.spec.versions[*].name}{"\n"}'
kubectl get --raw /apis/example.com/v1/widgets | head -c 200      # storage version: works
kubectl get --raw /apis/example.com/v1beta1/widgets               # fails

The failure reads roughly Error from server: conversion webhook for example.com/v1, Kind=Widget failed: ...: the tail of that message is the diagnosis.

Find the broken link.

kubectl get crd widgets.example.com -o jsonpath='{.spec.conversion.webhook.clientConfig}'
kubectl get endpointslices -n webhooks -l kubernetes.io/service-name=widget-converter
kubectl get pods -n webhooks -l app=widget-converter
kubectl logs -n webhooks deploy/widget-converter --tail=50

Signature → cause: x509: certificate signed by unknown authority → caBundle no longer matches the serving cert. connection refused / no endpoints → Service selector or port drift. Restarts in kubectl get pods → OOM or crashloop. Timeouts with healthy pods → NetworkPolicy blocking the API server. Also check spec.conversion.webhook.conversionReviewVersions contains a version the API server supports (v1 or v1beta1); an unsupported value fails every conversion.

Restore, with criteria. Roll back (kubectl rollout undo deploy/widget-converter -n webhooks) when the breakage started with a webhook deploy and the old binary still understands the current CRD schema. Fix forward when only config drifted: re-issue the caBundle, correct the selector, raise the memory limit. Rolling back is the wrong move if the CRD schema changed in the same release: the old binary will fail conversion on new fields, and you trade a 500 for silent field loss.

Do not set strategy: None unless every version's schema is identical. Otherwise the API server serves v1beta1 objects as v1 and drops fields on write.

Verify, then migrate. Round-trip a copy:

kubectl get widgets.v1beta1.example.com <name> -o yaml > /tmp/a.yaml
kubectl get widgets.v1.example.com <name> -o yaml > /tmp/b.yaml
diff <(yq '.spec' /tmp/a.yaml) <(yq '.spec' /tmp/b.yaml)

Then rewrite objects so status.storedVersions converges on the target version, and only then remove the old version from spec.versions. Watch apiserver_request_total{verb="WATCH"} and webhook p99 while you do it: a flapping webhook turns every watch into a retry storm.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Choose between a CRD and an aggregated API server.

Answer

Core answer

Default to a CRD. It is served by kube-apiserver itself through apiextensions-apiserver, stored in the cluster's etcd, and inherits RBAC, admission, discovery, list/watch, the status and scale subresources, CEL validation and conversion webhooks. You get all of that from a YAML file and no new process to run.

Aggregate only when you need something the CRD machinery structurally cannot do: storage that is not etcd (metrics out of a TSDB, records in an external system), protobuf on the wire, subresources beyond status and scale, or an API shape that is not Kubernetes-style resources. The price is a second API server on the control path that you build, secure, upgrade and page on.

Why the price is real

An aggregated API is registered as an APIService object. kube-apiserver's kube-aggregator proxies matching requests to a backend Service, so every call takes an extra hop: kube-apiserver → aggregator → Service ClusterIP → your pod, with a TLS connection to the backend. The aggregator pools connections, so steady-state cost is roughly one extra round trip, but the backend is now in the request path for that group, and its latency is your API's latency.

CRDAggregated API server
Storageetcd, same as built-ins; object capped by etcd's 1.5 MiB default max request size (kube-apiserver's own limit is 3 MiB)whatever you implement; can be external
Wire encodingJSON onlyJSON or protobuf
Subresourcesstatus, scaleany you implement
Ops surfacenone beyond the clustera Deployment, Service, serving cert, CA bundle in the APIService, its own upgrade cadence
Authn/authzinheritedmust delegate to kube-apiserver or implement
Blast radiusa broken conversion or validation webhook blocks writes to that CRDbackend down → 503 for that group, and discovery for the group fails

Failure modes and how you see them

  1. Aggregated backend unavailable. kube-apiserver returns 503 for that group's requests and discovery for the group fails. Clients that do full discovery (kubectl, controller-runtime's RESTMapper) can fail on unrelated commands. Detect with kubectl get apiservice v1beta1.example.io -o jsonpath='{.status.conditions[?(@.type=="Available")]}': Available=False, reason FailedDiscoveryCheck when the aggregator's discovery probe fails.

  2. CRD conversion webhook down. If you store v1alpha1 and serve v1, every read and write that crosses versions calls the webhook. Webhook down → apiserver returns 500 with the webhook error and writes to the CRD stop. Detect from apiserver logs and the error text on the failed request; the CRD's own status will not tell you.

  3. Non-structural schema. A v1 CRD that is not structural is rejected at apply time with condition NonStructuralSchema. You find out at deploy, not at runtime.

  4. APIService CA bundle mismatch or expired serving cert. Same Available=False path, reason FailedDiscoveryCheck: the aggregator cannot complete TLS to the backend.

Worked arithmetic (illustrative figures)

Say a CRD read is 15 ms p99 end to end. An aggregated backend whose own p99 is 12 ms adds the hop and TLS, so the client sees roughly 28–30 ms, and the backend's p99 now sits inside your API's p99, so its GC pause or slow query becomes your API's latency.

What would change my decision

If the data already lives in an external system and you would be copying it into etcd just to serve it, aggregate. If you need protobuf for a high-QPS watch, aggregate. Otherwise take the CRD, and if you hit a wall, the wall is almost always storage or encoding, not validation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Secure a multi-tenant operator.

Answer

Clarify and assume. I'd pin the tenancy model first, because it decides every control. Assume namespace-per-tenant: each tenant owns one or more namespaces labelled tenant: <id>, and one operator instance reconciles CRs across all of them. The operator is the threat surface: it holds a service account with permissions no tenant has, and it acts on objects tenants wrote.

Core answer. The failure is a confused deputy. Kubernetes RBAC authorizes the caller's identity, not the object's contents. When tenant A creates a Database CR, the API server checks tenant A's rights on databases in tenant-a; it never inspects what the CR references. The operator then reconciles with its own service account, which does have broad access. A CR pointing at tenant-b/db-password gets read by the operator, and the value lands wherever the CR says. Nothing in the default path stops it.

Three controls close that gap.

Scope the operator's identity. No cluster-admin. A ClusterRole for its own CRDs and read-only namespace access, plus a RoleBinding per tenant namespace for the resources it manages:

ResourceVerbsScope
databases (own CRD)get, list, watch, update (status subresource)ClusterRole
secretsget, list, watchRoleBinding per tenant ns
deploymentscreate, update, patch, deleteRoleBinding per tenant ns
eventscreate, patchClusterRole
namespacesget, list, watchClusterRole

Never *, and never escalate, bind, or impersonate: those turn a scoped identity back into a cluster-admin one.

Validate references at admission. Enforce same-namespace references in CEL, which is in-process and has no network dependency:

YAML
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
spec:
  failurePolicy: Fail
  validations:
  - expression: "object.spec.secretRef.namespace == object.metadata.namespace"
    message: "secretRef.namespace must equal the CR's namespace"

CEL can't fetch other objects, so anything cross-object ("does namespace X carry tenant label Y", "does this tenant own cloud project P") needs a webhook. Set failurePolicy: Fail and accept that a webhook outage blocks writes to that resource.

Don't rely on cross-namespace owner references. Kubernetes garbage collection ignores owner refs across namespaces. Dependents must live in the same namespace, or you track ownership yourself with a label plus a finalizer.

Trace the attack. Tenant A creates a Database in tenant-a with spec.secretRef: {name: db-password, namespace: tenant-b}. The API server admits it: tenant A has create on databases in its own namespace, and nothing checks the ref. The operator reads the CR, calls GET /api/v1/namespaces/tenant-b/secrets/db-password with its own SA, gets tenant B's credential, and writes it into a Deployment env var in tenant-a. Tenant A now holds tenant B's password. Detection: audit policy logging RequestResponse on secrets, alerting when the operator SA reads a Secret whose namespace tenant label differs from the CR's. Cost: full credential disclosure, plus every downstream system that credential reaches.

Trade-offs. Namespace-per-tenant gives real isolation but can't scope cluster-scoped objects: CRDs, ClusterRoles, webhooks are shared, so a bug there crosses tenants. Shared-namespace-with-labels is cheaper but every control becomes a label check a single bug bypasses. One operator watching all namespaces is simpler but is one high-privilege identity; one operator instance per tenant, each with an SA bound to a single namespace, shrinks the blast radius at the cost of N control planes to upgrade.

Other failure modes. Crafted names: validate with label selectors, not string prefixes, so tenant-a-evil doesn't match tenant-a. Owner transfer: a namespace relabelled to a new tenant while the operator still reconciles old CRs; watch namespace label changes. Compromised tenant workload: a pod reads its own SA token; if that SA has any binding outside its namespace, it pivots. Default-deny egress per tenant namespace, automountServiceAccountToken: false where the workload doesn't call the API, and projected bound tokens (default 1h) or workload identity federation instead of static cloud keys in Secrets.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Test an operator end to end.

Answer

What I'd say first

Assume Kubernetes 1.29 and controller-runtime v0.17+. "End to end" for an operator is three tiers, and the real work is deciding which tier each behaviour needs, because the cheap tiers are blind to the expensive behaviours.

  • Unit, fake client. Pure desired-state functions and condition transitions. Milliseconds, runs on every save.
  • envtest. A real kube-apiserver and etcd binary, no kubelet, no scheduler, no controllers. Catches defaulting, validation, pruning, conversion, RBAC on the status subresource, watch semantics, resourceVersion conflicts, owner-reference and finalizer rules. Startup is a couple of seconds.
  • kind/k3d. Adds kubelet, scheduler and real pods. This is the only tier where a child actually becomes Ready, where deletion blocks on a real finalizer, and where leader election runs against a real Lease.
  • Staging cluster. Adds the cloud provider: load balancers, IAM, CSI, real API throttling. Nightly, not per-PR.
tierwhat runscatchescost
unitfake clientdesired-state math, condition transitionsms
envtestapiserver + etcddefaulting, validation, RBAC, conversion, finalizers, conflicts~2–5 s startup
kind+ kubelet, schedulerchild readiness, real deletion, Lease leader election30–60 s per cluster
staging+ cloud providerLB/IAM/CSI, throttling, quotaminutes, nightly

The trade-off is coverage against flake and wall-clock. envtest on every PR, kind on merge, staging nightly. Pushing readiness waits into envtest is the common mistake: there is no kubelet, so Deployment.Status.ReadyReplicas stays 0 forever and the test either hangs or you fake the child status. At which point you are testing your fake, not the operator.

Why a crash between create and status write is survivable

Go
func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    var app v1alpha1.App
    if err := r.Get(ctx, req.NamespacedName, &app); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }
    var dep appsv1.Deployment
    err := r.Get(ctx, types.NamespacedName{Name: app.Name, Namespace: app.Namespace}, &dep)
    if apierrors.IsNotFound(err) {
        dep = buildDeployment(&app)
        if err := ctrl.SetControllerReference(&app, &dep, r.Scheme); err != nil {
            return ctrl.Result{}, err
        }
        if err := r.Create(ctx, &dep); err != nil {   // process killed here
            return ctrl.Result{}, err
        }
    }
    app.Status.ReadyReplicas = dep.Status.ReadyReplicas
    return ctrl.Result{}, r.Status().Update(ctx, &app)
}

Trace it. First pass: Get Deployment returns NotFound, Create succeeds, the process dies before Status().Update. On restart the informer cache syncs, Reconcile runs again, Get now finds the Deployment, the create branch is skipped, status is written. One Deployment, correct status. The property that saves you is that the create decision is derived from observed cluster state, not from app.Status.Phase. Key it off status and the restart creates a second Deployment; SetControllerReference permits one controller owner, so the second Create fails with AlreadyOwnedError, or with different names you silently get two.

Failure modes and how you detect them

  • Stale cache. The informer lags the apiserver; a reconcile reads an old object and writes a stale status. Detect with a conflict-injection test: bump the object out of band, assert the operator retries on resourceVersion conflict rather than clobbering.
  • Lost watch / relist. Kill the watch mid-test; assert the operator resyncs and converges without a restart.
  • Throttling. Set a low client-go QPS/burst, assert the workqueue backs off on 429 instead of hot-looping.
  • Leader failover. Two replicas, kill the leader; the Lease expires and the standby takes over. Idempotent reconcile is what makes the brief overlap harmless.
  • Deletion during provisioning. Delete the CR while a child is mid-create; the finalizer must drain the child and only then release, and the force-removal path must be documented and tested.

What changes the strategy: if the operator owns no children and only writes status, envtest is the whole story and kind is waste. If it provisions cloud resources, the ambiguous-outcome path (request sent, response lost) is the one that needs a contract test with a fake provider that can return "unknown" and be replayed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Observe and alert on operator health.

Answer

Assumptions: a controller-runtime operator, two or more replicas with leader election, Prometheus scraping /metrics, and tenant CRs sharing one cluster. If any of those is false, the alert set below changes: I'll say where.

Operator health has four layers, and only the bottom one should page a human. Top to bottom: the reconcile loop (rate, error ratio, duration), the workqueue (depth, oldest-item age, retries), the API client (request rate, error codes, client-side throttling), and resource convergence (is each CR actually where it should be). The first three tell you the operator is struggling; the fourth tells you users are affected. Alert on the fourth, and on sustained degradation of the first three. A single retry is not an incident.

SignalIllustrative thresholdWhat it catches
controller_runtime_reconcile_errors_total / controller_runtime_reconcile_total>5% over 15msystematic failure, not one flaky API call
controller_runtime_reconcile_time_seconds p99>2× the 7-day p99 baselineslow convergence, cache-miss loops
workqueue_depth>100 for 10mworker starvation
workqueue_queue_duration_seconds p99>30sreal backlog, not a burst
workqueue_retries_total rate>10/s for 10mhot-looping on a permanently failing object
`rest_client_requests_total{code=~"4295.."}`>1% over 5m
rest_client_rate_limiter_duration_seconds p99>100msclient-side throttling
leader_election_master_statussum ≠ 1 for 2msplit brain or no leader
reflector_short_watches_total rate>0.1/swatch churn, resync storm

Those numbers are a starting point I'd defend in review, not defaults: tune them against your own baseline before they page anyone.

The layer that actually matters is resource convergence, and it must not be built from high-cardinality labels. Derive gauges from CR status, labelled by kind and namespace only, never by name or UID:

  • operator_resource_stale_generation{kind}: count of CRs where metadata.generation != status.observedGeneration. Page if >0 for 10m.
  • operator_resource_deletion_stuck{kind}: CRs with a deletionTimestamp older than 5m. Page if >0 for 10m.
  • operator_resource_degraded{kind}: CRs with a Degraded condition true for >15m.
YAML
- alert: OperatorNotConverging
  expr: sum by (kind) (operator_resource_stale_generation) > 0
  for: 10m
  labels: {severity: page}
  annotations:
    runbook: operator-stale-convergence

Three failure modes worth naming. First, alerting on every retry: one bad CR backs off exponentially, workqueue_retries_total spikes to hundreds per minute, and you page on a single tenant's typo. Gate retry alerts on queue age too, or drop them and rely on the stale gauge. Second, cardinality: labelling by CR name or UID turns a 50-series metric into 500k and takes Prometheus down with it. Bound to kind and namespace; if you genuinely need per-CR detail, put it in a log or a trace, not a metric. Third, silent false convergence: reconciles return success, reconcile_errors_total stays at zero, but observedGeneration never advances because the controller writes status before applying. Only the resource-level gauge catches that.

For tracing, emit one OpenTelemetry span per reconcile with attributes controller, kind, namespace, result: never the CR name or spec body, which can carry tenant data. For synthetic coverage, create, update, and delete a canary CR in a dedicated namespace every 5m and measure end-to-end convergence; alert if p99 exceeds 60s. Watch controller_runtime_webhook_requests_total{code} and webhook latency separately, since a failing conversion webhook blocks every write to that kind.

What changes the decision: with a single replica, leader_election_master_status is always 1 and the alert is pure noise. Drop it. If the operator owns fewer than ~100 CRs, per-kind gauges are cheap and you can skip the workqueue layer entirely. Above ~100k CRs, you need the queue layer and sampling, because per-object gauges stop being affordable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Upgrade an operator safely.

Answer

Assumptions: one cluster, you own both the CRD and the controller image, and there are live CRs. The upgrade is three clocks that must not be conflated: the CRD's served/storage versions, the controller binary, and the state the controller manages (CRs plus anything external it provisions).

The answer: never change storage version and controller behaviour in the same step. Sequence:

  1. Add the new version to spec.versions with served: true, storage: false. Schema changes in this step must be additive only.
  2. Deploy the conversion webhook (if the two versions aren't structurally identical) and confirm it answers before anything is stored in the new version.
  3. Flip storage: true to the new version. New writes now land in v2; existing objects are still in v1.
  4. Roll the controller with a leader-safe strategy.
  5. Rewrite every stored object so status.storedVersions collapses to the new version.
  6. Only then remove the old version from spec.versions and drop old fields from the schema.

Why step 5 gates step 6. status.storedVersions is the apiserver's record of which versions exist in etcd. It only shrinks when an object is written. If you delete a version from spec.versions while it is still in storedVersions, the apiserver cannot decode those objects and returns errors on read for exactly those CRs: a partial outage that looks like data corruption. Check it with:

kubectl get crd widgets.example.com -o jsonpath='{.status.storedVersions}'

Migration is a Job that lists every CR and does a no-op update (kubectl get ... -o json | kubectl replace -f -, or a client-go loop calling Update with the same object). cert-manager ships this as a storage-version-migration Job for exactly this reason.

Why the webhook comes before the storage flip. Conversion runs on every read and write that crosses versions. If the webhook Service has no ready endpoints, the apiserver fails the request: conversion webhooks have no failurePolicy: Ignore escape hatch, unlike admission webhooks. A webhook outage during the flip is a read outage for every CR.

stepexact changegate to pass before next
1spec.versions += v2, served: true, storage: falseCRs still readable at v1
2conversion webhook Deployment, spec.conversion.strategy: Webhook, caBundle setwebhook returns 200 for a v1↔v2 round trip
3v2 storage: truenew writes land in v2
4controller image rollnew leader holds the Lease
5migration Job rewrites all CRsstoredVersions == [v2]
6drop v1 from spec.versions, drop old schema fieldsno client requests v1

Leader-safe rollout. Two replicas, RollingUpdate with maxUnavailable: 0. controller-runtime's default leader election uses a coordination.k8s.io/v1 Lease with LeaseDuration 15s, RenewDeadline 10s, RetryPeriod 2s; the new pod blocks until the old leader releases, so you get a clean handover rather than two controllers reconciling the same CR. If your reconciler is not idempotent, that handover is where you find out.

Failure modes and detection.

  • Stuck storedVersions: the migration Job crashed halfway. Detect by comparing storedVersions against the count of CRs; make the Job re-list rather than checkpoint so it is resumable.
  • Webhook timeout during rollout: reads of old-version CRs return 500. Detect with apiserver_request_total{code="500"} on the CRD's resource, and alert on it before the flip.
  • Schema pruning data loss: dropping a field from the OpenAPI schema with preserveUnknownFields: false means the apiserver silently prunes that field from stored objects on the next write. Stay additive-only until step 6.
  • Half-migrated status: the controller writes v2-shaped status while some CRs are still v1. Keep the controller able to read both until step 5 completes.

Trade-offs. Rollback is cheap before step 3 (revert the CRD, redeploy the old image) and expensive after step 5, because objects are now stored in v2. Past that point, forward repair, ship a fixed controller, is the only honest option. If the two versions are structurally identical, skip the conversion webhook entirely and use strategy: None; that removes the biggest failure mode. If they are not, a feature gate that keeps the old code path alive for one release is cheaper than running a second controller.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Model a one-shot operation in Kubernetes.

Answer

Assumptions. The operation is discrete and bounded: it finishes or it fails, it isn't a long-running service. Either the work runs as a container, or it's a side effect on a system outside the cluster (a database, a payment provider, a bucket). Cluster is 1.28+.

Core answer. If the work is a container, use a batch/v1 Job. Don't invent a CRD for that. Reach for a custom Operation resource only when the side effect is external and you need durable intent, dedup and an audit trail that outlives the pod.

Job specifics for a one-shot:

  • completions: 1, parallelism: 1.
  • restartPolicy: Never or OnFailure: Always is rejected by Job validation.
  • backoffLimit defaults to 6, so up to 7 pod attempts before the Job is marked Failed.
  • activeDeadlineSeconds bounds wall-clock; ttlSecondsAfterFinished (GA 1.23) deletes the Job and its pods N seconds after it finishes. Set it, or completed Jobs pile up in etcd.
  • podFailurePolicy (introduced 1.25) lets you fail fast on a non-retryable exit code instead of burning all 7 attempts.

The container must be idempotent regardless: a pod can be recreated after a node dies before its status is recorded, so "succeeded" is not proof the side effect ran exactly once.

CRD sketch when the side effect is external:

YAML
apiVersion: ops.example.com/v1
kind: Operation
metadata:
  name: rotate-db-cred-7f3a
spec:
  targetRef: {apiVersion: ..., kind: Database, name: orders}
  parameters: {rotate: true}
  deadline: "2025-01-01T00:00:00Z"
status:
  observedGeneration: 3
  conditions:
    - type: Accepted
    - type: Succeeded
  resultRef: {name: secret-abc}

Dedup trace. Controller sees generation 3, calls the external API with Idempotency-Key: <metadata.uid>, the external system records the key, controller writes Succeeded and observedGeneration: 3. Controller crashes before writing status. New controller reads generation 3, calls again with the same UID, the external system returns the cached result, controller writes status. One side effect, two calls. That's the contract: at-least-once delivery, exactly-once effect via the UID key.

Failure modes:

  • Non-idempotent external API → duplicate charges. Detect: two results for one UID, or the external dedup table growing without bound.
  • Finalizer used to keep history → namespace deletion hangs. Finalizers are for real cleanup (delete the external resource), not retention. Use ttlSecondsAfterFinished or a reaper.
  • Payload in spec → etcd rejects at 1.5 MiB (--max-request-bytes default 3 MiB on the API server, 1.5 MiB on etcd). Put big payloads in a ConfigMap or object store and reference them.
  • Cancellation: only set spec.cancelRequested if the operation is actually cancellable. A half-applied migration can't be cancelled, only rolled forward.

RBAC: the requester needs create on operations, not on the target. The controller's ServiceAccount holds the target permission. That privilege boundary is the point of the CRD.

What would change my decision. A single API call with no retry semantics: a subresource or a plain REST endpoint on your own service is simpler than a CRD. A container: Job. Recurring: CronJob. Long-running: it isn't a one-shot operation, it's a controller.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design backup and restore behavior in an operator.

Answer

Assumptions and core design. Kubernetes 1.29+, controller-runtime v0.17, and a CSI driver implementing snapshot.storage.k8s.io/v1. The operator owns three CRDs and never moves bytes itself: it creates a child snapshot object and watches it.

  • BackupPolicy (mutable, namespaced): schedule (cron, e.g. 0 2 * * *), retention: {maxCount: 7, maxAge: 168h}, selector, consistency: Crash|Application, hooks: {pre, post}, destination: {bucket, region}, encryption: {keyRef}, paused.
  • BackupRequest (immutable once created): policyRef, targetUID. The PVC's metadata.uid captured at creation, so a recreated PVC with the same name is not silently backed up. consistency, timeout: 1h. Status: phase, snapshotRefs, startedAt, completedAt, verifiedAt.
  • RestoreRequest (immutable): backupRef, targetNamespace, existingResourcePolicy, restorePVs.

The reconcile loop creates a VolumeSnapshot (or a Velero Backup), then watches the child. Success is status.readyToUse: true on the VolumeSnapshot, not the create call returning. A VolumeSnapshot can sit Pending for the entire window if the snapshot controller is down, and a Velero Backup can reach PartiallyFailed: both are invisible if you mark success on creation.

Consistency. Crash-consistent means snapshotting the running volume. Postgres replays WAL on restore, so this is usually enough and costs nothing. Application-consistent means a pre-hook (pg_start_backup(), FLUSH TABLES WITH READ LOCK, redis-cli BGSAVE), then the snapshot, then a post-hook. Velero's exec hook waitTimeout defaults to 30s; if the hook exceeds it the backup proceeds anyway, so set it explicitly and fail the request when the hook errors.

Trade-offs. CSI snapshot vs Velero file-level (Kopia/Restic). CSI is copy-on-write: a 100 GiB gp3 volume snapshots in seconds, but the snapshot lives in the storage backend, so restoring to a different cloud needs a copy step. File-level reads every file at roughly 50–100 MB/s per node, 100 GiB is ~20–35 minutes, but it is portable and supports per-path restore. Pick CSI when RPO is minutes and you stay on one backend; pick file-level for cross-cloud or single-file recovery. Quiesce vs snapshot: quiescing the leader costs downtime. Snapshot a replica instead: crash-consistent with no outage, at the cost of replica lag, usually under a second.

Failure modes.

  1. Snapshot never ready. readyToUse stays false because the VolumeSnapshotClass is missing. Detection: phase: InProgress past spec.timeout; emit SnapshotNotReady and skip retention pruning so the window does not silently shrink.
  2. Restore silently skips. Velero's default existingResourcePolicy: none skips resources that already exist, so the restore reports success while the app runs old data. Detection: status.progress.itemsRestored < status.progress.totalItems. Record it, do not treat it as failure.
  3. Cross-tenant read. A RestoreRequest in namespace A referencing a Backup in namespace B. An admission webhook must deny unless the requester's ServiceAccount has get on that Backup.
  4. Finalizer deadlock. The BackupRequest finalizer deletes the snapshot; if the CSI driver is uninstalled it never clears and the namespace hangs in Terminating. Add --finalizer-timeout=5m, then remove the finalizer and emit an event.
  5. Retention vs legal hold. maxCount: 7 prunes the oldest backup; if it carries backup.example.com/hold: legal, deleting it is spoliation. Check the annotation before delete.

Restore testing. A weekly RestoreRequest into a scratch namespace, then pg_amcheck or a row-count comparison against the restored data. A backup that has never been restored is a hypothesis, not a control.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design an operator-controlled application upgrade.

Answer

Assumptions I'd state first: Kubernetes, controller-runtime v0.17 on Go 1.22, the app is a 3-replica StatefulSet on Postgres, single cluster, and the operator is the only writer of the app's spec. Multi-cluster or a single-replica stateful app changes the design, and I'd say so before drawing anything.

Core answer. An operator-controlled upgrade is a reconcile loop that treats the target version as desired state and drives a phase machine toward it, persisting the phase in status so a controller restart resumes instead of restarting. Three things make it safe: the transition is validated before anything moves, the binary rollout is separated from the data migration, and every step is gated on a health signal with a timeout.

CRD shape: spec.version (desired), spec.paused, status.currentVersion, status.phase, status.conditions[] carrying observedGeneration. The operator only acts when metadata.generation == status.observedGeneration, so a stale reconcile can't overwrite a newer spec.

Phases: Validating → PreflightBackup → RollingOut → Migrating → Verifying → Done, plus RollingBack and Failed.

Supported transitions are declared, never inferred:

Go
// controller-runtime v0.17, Go 1.22
func nextStep(cur, want string, supported map[string][]string) (string, error) {
    if cur == want {
        return "", nil
    }
    for _, n := range supported[cur] {
        if n == want {
            return want, nil
        }
    }
    return "", fmt.Errorf("unsupported transition %s -> %s", cur, want)
}

With supported = {"1.4": {"1.5"}, "1.5": {"1.6"}, "1.6": {}}: nextStep("1.4", "1.5") returns "1.5", nil; nextStep("1.4", "1.6") returns "", error. The skip is blocked before a single pod moves. An operator that reasons "1.4 < 1.6, go" will happily skip the migration that 1.5 introduced.

Rollout order and gates. For a 3-replica StatefulSet, podManagementPolicy: OrderedReady plus a PodDisruptionBudget with minAvailable: 2 keeps quorum (2 of 3) intact. One pod at a time; wait for readiness plus 5 minutes of steady state before the next. Gate signals, with hypothetical thresholds: p99 latency under 300 ms, 5xx rate under 0.5%, readiness probe passing 3 consecutive periods. A failed gate sets phase: RollingBack and stops: it does not retry the same step forever.

Data migration is separate and ends irreversible. Expand/contract: add the column nullable, dual-write, backfill, switch reads, drop the old column a release later. The binary rollback window closes at the contract step, so the operator requires spec.allowDestructive: true before running it.

strategyrollback speedcostneeds
rollingslow: re-roll N-11xN/N-1 schema compat
blue-greenseconds: flip Service2xboth versions read/write the same schema
canary 1 of 10fast: shift traffic1.1xtraffic splitting, per-version metrics

Rolling is the default because it's cheapest; blue-green buys fast rollback at double capacity; canary limits blast radius but needs per-version metrics or you can't attribute the regression. When not to use any of this: a single-replica stateful app with no N-1 compatibility. Take a maintenance window: an operator there adds failure modes without buying availability.

Failure modes. Operator restart mid-rollout: the phase is in status, and each step is "ensure pod i is at version X", not "increment a counter", so resume is idempotent. Two operator replicas without a coordination.k8s.io Lease both drive the rollout: leader election is not optional. CR deleted mid-upgrade: a finalizer holds it until Done or Failed, otherwise you orphan a half-migrated database. PDB blocking eviction stalls the rollout silently; surface an UpgradeStalled condition with reason PodDisruptionBudget. Downgrade is only allowed when the previous binary reads the current schema: otherwise a spec.version below status.currentVersion is rejected outright.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Retire an operator and CRD safely.

Answer

What I'd say first

Assumptions: one cluster, CRD widgets.example.com with versions v1alpha1 (storage) and v1beta1, operator is a Deployment in example-system, no aggregated APIService in play. Multi-cluster means this runs per cluster, CRD deleted last in each.

The whole job is ordering. Four drains, in this order: writers, finalizers, stored versions, then the CRD. Deleting the CRD first is the one irreversible mistake: it triggers deletion of every CR, and any CR carrying a finalizer sits in Terminating while the CRD's own customresourcecleanup.apiextensions.k8s.io finalizer holds the CRD in Terminating. You can't recreate the CRD under that name until it clears, and the operator's cleanup code never ran.

1. Inventory

Shell
kubectl get crd widgets.example.com \
  -o jsonpath='{range .spec.versions[*]}{.name}{" served="}{.served}{" storage="}{.storage}{"\n"}{end}'
kubectl get crd widgets.example.com -o jsonpath='{.status.storedVersions}'
kubectl get widgets.example.com -A --no-headers | wc -l
kubectl get widgets.example.com -A \
  -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}{" "}{.metadata.finalizers}{"\n"}{end}'

status.storedVersions is the field that decides whether you may remove a version from spec.versions: the apiserver rejects the update while a version is still listed there. Finalizer strings are qualified names like example.com/widget-cleanup; grep the operator source for the ones it adds.

Who else calls it: kubectl get clusterrole,role -A -o json | jq -r '.items[] | select([.rules[]?.resources[]?] | any(. == "widgets")) | .metadata.name', plus apiserver audit logs filtered on the group.

2. Freeze writers

Remove create on widgets from every ClusterRole and Role that has it, including the operator's. That's the gate: enforced by RBAC, no webhook, reversible. If you want a clearer error, a ValidatingAdmissionPolicy (GA in 1.30) with a CEL expression denying CREATE on the group is the current way; a failurePolicy: Fail webhook is the older one and adds an outage surface of its own.

3. Drain finalizers

Scale the operator back up with only its delete path enabled, or run it once with a flag that reconciles deletions only. Watch for CRs that don't clear. If the operator is gone for good, strip the finalizer by hand:

Shell
kubectl patch widgets.example.com foo -n team-a --type=merge -p '{"metadata":{"finalizers":null}}'

Only after you've confirmed the external resource it was protecting is gone or handed over. This is the step where you lose data, not the CRD delete.

4. Drain stored versions

Rewrite every object so it's persisted at the storage version:

Shell
for ns in $(kubectl get widgets.example.com -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\n"}{end}' | sort -u); do
  for name in $(kubectl get widgets.example.com -n "$ns" -o jsonpath='{.items[*].metadata.name}'); do
    kubectl get widgets.example.com "$name" -n "$ns" -o json | kubectl replace -f - >/dev/null
  done
done
kubectl get crd widgets.example.com -o jsonpath='{.status.storedVersions}'

Example: 12,000 CRs at roughly 50 objects/s is about four minutes. One pass, not parallel per namespace, so you don't hammer etcd. Re-check storedVersions; if the old version is still listed you missed objects (cluster-scoped, or a namespace the loop skipped). Only when it lists just the storage version can you drop the old entry from spec.versions.

5. Remove webhooks and conversion

If spec.conversion.strategy is Webhook, it points at the operator's Service. Set it to None after step 4: before that, reads of non-storage versions need it. Then delete the Validating and MutatingWebhookConfigurations whose rules match the group. A failurePolicy: Fail webhook left pointing at a deleted Service makes every CREATE and UPDATE on the CRD fail with failed calling webhook; you'll see it in apiserver audit logs and kubectl get events.

6. Delete the CRD, then the operator

Shell
kubectl delete crd widgets.example.com
kubectl -n example-system delete deploy widget-operator
kubectl delete clusterrole widget-operator

CRD first, operator second: a running operator whose informer can't resolve the kind logs no matches for kind "Widget" in version "example.com/v1" and crashloops if it treats that as fatal. Deleting the CRD while nothing is watching it is quiet.

7. What to have in hand

Backup: kubectl get widgets.example.com -A -o yaml > widgets-backup.yaml before step 3, plus the CRD manifest. Rollback is re-applying the CRD and the backup, which only works if the CRD actually left the cluster, hence the ordering. Audit evidence: the RBAC diff, the finalizer-strip list with who approved each, and the storedVersions output before and after.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a database operator API.

Answer

Clarify and assume. I'll assume Kubernetes 1.29+, CRDs at apiextensions.k8s.io/v1, controller-runtime, and one engine (Postgres 16) to keep it concrete. The operator owns the cluster lifecycle: provisioning, failover, backup, upgrade. Users own schemas, roles and data. That boundary is the whole design.

Core answer. The API is two halves: spec is user intent, status is observed reality, and the controller's only job is to drive one to the other. Identity lives in metadata.name and never encodes anything mutable: no postgres-16-prod names, because an upgrade would force a rename and orphan the data. Version, topology and size are spec fields.

YAML
apiVersion: db.example.com/v1
kind: DatabaseCluster
metadata:
  name: orders-db          # stable identity
spec:
  engine: {name: postgres, version: "16.3"}
  instances: 3             # default 1, min 1, max 15
  storage: {class: gp3, size: 100Gi}
  availability: {mode: multiAZ, minSyncReplicas: 1}
  backup: {schedule: "0 2 * * *", retentionDays: 7, destinationRef: {name: s3-creds}}
  credentials: {secretRef: {name: orders-db-auth, key: password}}
  deletionPolicy: Retain
status:
  observedGeneration: 12
  conditions:
    - {type: Ready, status: "True", reason: AllReplicasReady}
    - {type: Progressing, status: "False", reason: UpgradeComplete}
  endpoints: {primary: orders-db-rw.svc, reader: orders-db-ro.svc}
  members: [{name: orders-db-0, role: primary, ready: true}]
  currentVersion: "16.3"

Why it behaves this way. status.observedGeneration is the mechanism that answers "did my edit land?" The API server bumps metadata.generation on every spec write; the controller copies it into status only after a successful reconcile. If observedGeneration < generation for more than a few minutes, the controller is stuck or crashed: that's your alert, not a guess.

Conditions follow the standard type/status/reason/message/lastTransitionTime schema so kubectl wait --for=condition=Ready works and dashboards don't need custom parsing.

Ownership. The operator creates a StatefulSet, two Services, a Secret and a CronJob, all with ownerReferences pointing at the DatabaseCluster, so Kubernetes garbage-collects them. A finalizer (db.example.com/finalizer) runs the deletion policy: Retain leaves the PVCs and drops only the CR; Delete removes data. Credentials are always a SecretKeySelector, never inline: inline secrets land in etcd and in every kubectl get -o yaml.

Trade-offs. One CRD with a mode field versus separate CRDs: I split DatabaseBackup out because backups have an independent lifecycle. You create and expire them without touching the cluster. The deciding criterion is lifecycle coupling, not field count. For escape hatches, a spec.podTemplate passthrough lets users set things the operator doesn't model, but it breaks the contract: the operator can no longer guarantee failover semantics. I'd rather expose a narrow extraConfig map and document the rest as unsupported.

Failure modes.

  • Stuck finalizer: the controller can't reach the DB to drop it, the object sits in Terminating, and namespace deletion blocks. Detect with a DeletionBlocked condition and an alert on Terminating > 10 min.
  • Status drift: reconcile crashes after the spec write; observedGeneration never catches up. Alert on mismatch > 5 min.
  • Upgrade breakage: adding a required field to v1 rejects stored objects. Use a conversion webhook and keep the old version served until all objects are migrated.

Versioning. Ship v1alpha1, then v1 once the schema survives one real upgrade. Never mutate a served version's semantics in place.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Decide whether to build an operator for a service.

Answer

The 90-second answer

Assume you're on Kubernetes, the service has a declarative desired state, and you already have a Helm chart or Terraform module that applies it. My default is don't build one. Build an operator only when three things hold at once: the desired state must be continuously re-asserted against drift you don't control; the lifecycle has ordered, stateful steps (failover, backup/restore, version upgrade) that a one-shot apply can't express; and the domain API is stable enough that you'll ship it as v1 and keep it for years.

Miss any of those and use what you have: a Helm chart plus a CI job, a managed service, or an external controller. An operator is a control loop you now own, page on, and upgrade forever.

Why a control loop, concretely

helm upgrade is edge-triggered: it computes a diff once and exits. If someone kubectl edits a Deployment at 03:00, nothing corrects it until the next pipeline run. A controller is level-triggered: it watches, and on every event (plus a periodic resync, 10 hours by default in controller-runtime) it compares observed state to spec and acts. That's the entire value proposition, and the entire cost: your reconcile function runs on every event, so it must be idempotent.

The signals that decide it:

SignalBuildDon't build
Manual lifecycle toil≥ 2 h/engineer/week, recurringOne-off migrations
Drift sourceExternal actor mutates state (autoscaler, another controller, humans)Only your pipeline writes
Lifecycle stepsOrdered: quorum-safe upgrade, restore-from-backup, failoverStateless rollout
API stabilityYou can commit to v1 for 2+ yearsSpec still churning weekly
Blast radiusNamespaced, RBAC-scopedCluster-scoped, touches nodes or CRDs

Arithmetic for the toil line: 3 clusters × 2 upgrades/month × 45 min = 4.5 h/month ≈ 54 h/year. A minimal operator is 4–8 engineer-weeks to first release, plus roughly 20% ongoing for dependency bumps: client-go tracks Kubernetes releases, so you re-vendor about every 4 months. Break-even lands around year two, and only if the toil is genuinely recurring.

Failure modes and how you see them

  • Hot loop. A reconcile that writes to an object it also watches re-triggers itself. Symptom: API server request rate climbs, workqueue_depth and rest_client_requests_total spike. The default rate limiter (5 ms → 1000 s exponential, 10 qps / 100 burst) hides it until it doesn't. Watch controller_runtime_reconcile_total{result="error"} and API priority-and-fairness metrics.
  • Stuck reconcile. A finalizer added but never removed blocks deletion forever. Symptom: the object sits in Terminating, kubectl get <cr> -o yaml shows deletionTimestamp set with the finalizer still present. Pair every finalizer add with a timeout and a metric.
  • Webhook outage. A validating webhook with failurePolicy: Fail and the default 10 s timeout rejects every matching write when its pod is down: including the operator's own. Keep rules narrow, and prefer failurePolicy: Ignore for validation that isn't safety-critical.
  • Blast radius. A cluster-scoped CRD with a bad default breaks every namespace at once. Stay namespaced unless you truly need cluster scope.

What would change my mind

If the service is a managed offering with an upstream operator already maintained (a database with a vendor operator, say) consume it rather than write one. If the only justification is "so users can kubectl apply our thing," that's a CRD plus a controller you don't need; ship a Helm chart. And if the lifecycle logic is really an imperative script, an operator just hides it behind a control loop: fix the script first.

Curated: · Written: · Reviewed:

Difficulty: Hard