Kubernetes operators in Java with Spring Boot

An operator is a program that keeps something in a Kubernetes cluster the way a custom resource describes it, by comparing what should exist with what does and fixing the difference, over and over. This page explains that reconcile loop, runs a model of it and the health probes an operator pod needs, and shows the Java Operator SDK code for a Spring Boot 4 operator.

Share

Contents

What an operator is

Kubernetes manages built-in resources such as Deployments and Services with controllers: programs that watch a kind of resource and make the cluster match what it describes. A Deployment says "three pods of this image", and its controller creates, replaces or deletes pods until that is true. An operator applies the same pattern to your own kind of resource. You define a custom resource, for example a Shop with an image and a replica count, and the operator turns each Shop into the Deployments, Services, ConfigMaps and database schemas it needs.

The heart of every operator is the reconcile loop, and three properties make it robust:

  • Level-triggered: the reconciler is told only "this resource may need attention". It then reads the complete current state and works out what to do, instead of acting on what an event said changed. A missed or repeated event therefore does no harm.
  • Idempotent: running the reconciler twice on the same state does nothing the second time. Kubernetes and the operator framework both deliver events more than once, and resynchronise periodically.
  • Status reporting: the reconciler writes what it observed to the resource's status, including observedGeneration, so users and tools can tell whether the latest spec has been applied.
Building blocks of a Java operator
PieceProvided byRole
Custom resource definition (CRD)YAML, generated from a Java classRegisters the new resource kind with the API server
Custom resource classfabric8 Kubernetes client 7Java type with spec and status
ReconcilerJava Operator SDK 5Your reconcile logic, called on every relevant event
Dependent resources and @WorkflowJava Operator SDK 5Declarative management of the resources an operator owns
Spring Boot starteroperator-framework-spring-boot-starter 6.6Registers reconciler beans, configures the client, starts the operator
Probes and metricsSpring Boot ActuatorLiveness, readiness and metrics for the operator's own pod

The Java Operator SDK (JOSDK) is a CNCF project from the Operator Framework. Its Spring Boot starter 6.6 is built on Spring Boot 4.1, JOSDK 5.5 and the fabric8 client 7.8, according to its parent POM. No Kubernetes cluster and none of these libraries are available where this page was built, so the JOSDK examples are marked as not run; they were checked against the JOSDK documentation. The two programs shown running are a plain-Java model of the reconcile logic and the Spring Boot health probes that the operator's pod uses.

The reconcile loop, modelled

The reconcile logic decides everything else, and it can be written and tested as plain Java. This model keeps the "cluster" in a map and reconciles a Shop through the five situations an operator meets most often:

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

// A plain-Java model of a reconciler: compare desired state with actual state and act on
// the difference. It is NOT the Kubernetes API; it shows the logic an operator implements.
public class ReconcileModel {

    record Spec(String image, int replicas) {
    }

    record Deployment(String name, String image, int replicas) {
    }

    // what the cluster holds: deployments by name, as the API server would return them
    static final Map<String, Deployment> cluster = new TreeMap<>();

    static long generation = 1;        // metadata.generation: bumped on every spec change
    static long observedGeneration;    // status.observedGeneration: written by the operator

    // the reconciler: reads the WHOLE current state every time, never the event's delta
    static List<String> reconcile(String name, Spec spec) {
        List<String> actions = new ArrayList<>();
        Deployment desired = new Deployment(name + "-web", spec.image(), spec.replicas());
        Deployment actual = cluster.get(desired.name());
        if (actual == null) {
            cluster.put(desired.name(), desired);
            actions.add("create " + desired);
        } else if (!Objects.equals(actual, desired)) {
            cluster.put(desired.name(), desired);
            actions.add("update " + actual + " -> " + desired);
        }
        observedGeneration = generation;
        return actions.isEmpty() ? List.of("nothing to do") : actions;
    }

    static void run(String why, String name, Spec spec) {
        System.out.println(why);
        reconcile(name, spec).forEach(a -> System.out.println("  " + a));
        System.out.println("  status: observedGeneration " + observedGeneration
                + " of generation " + generation);
    }

    public static void main(String[] args) {
        Spec spec = new Spec("shop:1.4", 2);
        run("1. custom resource created", "shop", spec);
        run("2. same event delivered again (or a periodic resync)", "shop", spec);

        spec = new Spec("shop:1.5", 3);
        generation++;
        System.out.println("3. spec changed: generation " + generation
                + ", observedGeneration still " + observedGeneration + " until reconciled");
        run("   reconcile", "shop", spec);

        cluster.put("shop-web", new Deployment("shop-web", "shop:1.5", 1));
        run("4. someone scaled the deployment to 1 by hand (drift)", "shop", spec);

        cluster.remove("shop-web");
        run("5. someone deleted the deployment", "shop", spec);
    }
}
Output
1. custom resource created
  create Deployment[name=shop-web, image=shop:1.4, replicas=2]
  status: observedGeneration 1 of generation 1
2. same event delivered again (or a periodic resync)
  nothing to do
  status: observedGeneration 1 of generation 1
3. spec changed: generation 2, observedGeneration still 1 until reconciled
   reconcile
  update Deployment[name=shop-web, image=shop:1.4, replicas=2] -> Deployment[name=shop-web, image=shop:1.5, replicas=3]
  status: observedGeneration 2 of generation 2
4. someone scaled the deployment to 1 by hand (drift)
  update Deployment[name=shop-web, image=shop:1.5, replicas=1] -> Deployment[name=shop-web, image=shop:1.5, replicas=3]
  status: observedGeneration 2 of generation 2
5. someone deleted the deployment
  create Deployment[name=shop-web, image=shop:1.5, replicas=3]
  status: observedGeneration 2 of generation 2
  • Step 1: no Deployment existed, so the reconciler created shop-web with 2 replicas of shop:1.4 and recorded observedGeneration 1.
  • Step 2: the same input again found the Deployment already right and did nothing. This is the idempotence that makes repeated events and periodic resyncs safe.
  • Step 3: the spec change raised metadata.generation to 2, which Kubernetes does on every spec change. Until the reconcile ran, observedGeneration was still 1, which is how a client knows the change is not applied yet. Afterwards both were 2.
  • Step 4: someone scaled the Deployment to 1 by hand. The reconciler did not need an event describing that change; it compared the whole desired state with the whole actual state and set the replicas back to 3.
  • Step 5: the Deployment was deleted, and the next reconcile simply created it again.

Steps 4 and 5 are why level-triggered design matters. An operator that only reacted to "spec changed" events would never notice drift. In a real operator, the framework triggers a reconcile when the custom resource changes, when an owned resource such as the Deployment changes, and at a regular interval, and the reconciler always does the same comparison.

The custom resource (not run)

The resource kind is a Java class extending fabric8's CustomResource, with separate classes for the spec, which users write, and the status, which the operator writes:

Java
@Group("shop.example.com")
@Version("v1")
public class Shop extends CustomResource<ShopSpec, ShopStatus> implements Namespaced {
}

public class ShopSpec {
    private String image;
    private int replicas = 1;
    // getters and setters
}

public class ShopStatus {
    private long observedGeneration;
    private String phase;            // for example Ready or Progressing
    private String message;
    // getters and setters
}
YAML
apiVersion: shop.example.com/v1
kind: Shop
metadata:
  name: shop
  namespace: retail
spec:
  image: registry.example.com/shop:1.5
  replicas: 3

The CRD itself, the YAML that registers shops.shop.example.com with the API server, is generated from these classes at build time by fabric8's CRD generator, so the Java model and the schema cannot drift apart. Apply it to the cluster before the operator starts; JOSDK can check at start-up that the CRD is installed.

A reconciler with Java Operator SDK (not run)

The reconciler receives the current custom resource, already read from a local cache, and returns what to update on it. Resources the operator owns are declared as dependent resources, and JOSDK creates, updates and deletes them to match their desired state:

Java
@ControllerConfiguration
@Workflow(dependents = @Dependent(type = ShopDeployment.class))
@Component
public class ShopReconciler implements Reconciler<Shop>, Cleaner<Shop> {

    @Override
    public UpdateControl<Shop> reconcile(Shop shop, Context<Shop> context) {
        // the workflow has already reconciled ShopDeployment when this runs
        Deployment deployment = context.getSecondaryResource(Deployment.class).orElseThrow();
        boolean ready = Objects.equals(deployment.getStatus().getReadyReplicas(),
                shop.getSpec().getReplicas());

        ShopStatus status = new ShopStatus();
        status.setObservedGeneration(shop.getMetadata().getGeneration());
        status.setPhase(ready ? "Ready" : "Progressing");
        shop.setStatus(status);
        return UpdateControl.patchStatus(shop);
    }

    @Override
    public DeleteControl cleanup(Shop shop, Context<Shop> context) {
        // release anything outside Kubernetes, such as a database schema
        return DeleteControl.defaultDelete();
    }
}

public class ShopDeployment extends CRUDKubernetesDependentResource<Deployment, Shop> {

    @Override
    protected Deployment desired(Shop shop, Context<Shop> context) {
        return new DeploymentBuilder()
                .withNewMetadata()
                    .withName(shop.getMetadata().getName() + "-web")
                    .withNamespace(shop.getMetadata().getNamespace())
                .endMetadata()
                .withNewSpec()
                    .withReplicas(shop.getSpec().getReplicas())
                    // selector, labels and pod template with shop.getSpec().getImage()
                .endSpec()
                .build();
    }
}
  • desired describes the target, exactly like the model's desired Deployment. JOSDK compares it with the actual Deployment, applies the difference with server-side apply, and sets the Shop as its owner, so Kubernetes garbage-collects the Deployment when the Shop is deleted.
  • Owned resources are watched as well. When someone edits or deletes shop-web, the change triggers a reconcile of its Shop, which is how the drift in steps 4 and 5 of the model is detected.
  • UpdateControl.patchStatus writes only the status. UpdateControl.noUpdate() writes nothing, and rescheduleAfter(Duration) asks for another reconcile later, for example while waiting for an external system.
  • Implementing Cleaner makes JOSDK add a finalizer to each Shop. Kubernetes then keeps a deleted Shop until cleanup has run, which is the place to release resources outside the cluster that owner references cannot remove.
  • An exception from reconcile is retried with exponential backoff by default. Throwing is the right answer to a temporary failure, such as an unreachable registry.

With the Spring Boot starter, a reconciler that is a Spring bean is registered with the operator automatically, and it can inject other beans like any Spring component. The starter also configures the fabric8 KubernetesClient, which finds its cluster from ~/.kube/config during development or from the service account when running in a pod.

Health probes for the operator pod

The operator is itself a Deployment in the cluster, and Kubernetes needs to know whether its pod is alive and whether it should take traffic. Spring Boot exposes both as health groups. This program shows how they react to the application's availability state:

Java
package demo.operator.probes;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.LivenessState;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

public class OperatorProbes {

    @SpringBootApplication
    static class OperatorApplication {
    }

    static void probe(HttpClient http, int port, String path) throws Exception {
        HttpResponse<String> response = http.send(HttpRequest.newBuilder(
                URI.create("http://localhost:" + port + path)).build(),
                HttpResponse.BodyHandlers.ofString());
        System.out.println("  GET " + path + " -> " + response.statusCode() + " "
                + response.body());
    }

    static void both(HttpClient http, int port) throws Exception {
        probe(http, port, "/actuator/health/liveness");
        probe(http, port, "/actuator/health/readiness");
    }

    public static void main(String[] args) throws Exception {
        try (ConfigurableApplicationContext context = SpringApplication.run(
                OperatorApplication.class, "--server.port=0", "--spring.main.banner-mode=off",
                "--logging.level.root=WARN",
                // switched on automatically when Spring Boot detects Kubernetes
                "--management.endpoint.health.probes.enabled=true")) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();

            System.out.println("After start-up:");
            both(http, port);

            // e.g. this replica lost leader election and should receive no traffic
            AvailabilityChangeEvent.publish(context, ReadinessState.REFUSING_TRAFFIC);
            System.out.println("After ReadinessState.REFUSING_TRAFFIC:");
            both(http, port);

            // e.g. the reconcile loop is stuck: let Kubernetes restart the pod
            AvailabilityChangeEvent.publish(context, LivenessState.BROKEN);
            System.out.println("After LivenessState.BROKEN:");
            both(http, port);
        }
    }
}
Output
After start-up:
  GET /actuator/health/liveness -> 200 {"status":"UP"}
  GET /actuator/health/readiness -> 200 {"status":"UP"}
After ReadinessState.REFUSING_TRAFFIC:
  GET /actuator/health/liveness -> 200 {"status":"UP"}
  GET /actuator/health/readiness -> 503 {"status":"OUT_OF_SERVICE"}
After LivenessState.BROKEN:
  GET /actuator/health/liveness -> 503 {"status":"DOWN"}
  GET /actuator/health/readiness -> 503 {"status":"OUT_OF_SERVICE"}
  • After start-up, both /actuator/health/liveness and /actuator/health/readiness answered 200 UP.
  • Publishing ReadinessState.REFUSING_TRAFFIC turned readiness into 503 OUT_OF_SERVICE, while liveness stayed UP. Kubernetes stops sending traffic to such a pod, for example to its webhook or metrics endpoint, but does not restart it.
  • Publishing LivenessState.BROKEN turned liveness into 503 DOWN. Kubernetes restarts a pod whose liveness probe keeps failing, which is the right response to a reconcile loop that is stuck.

The program enables the probe endpoints with management.endpoint.health.probes.enabled=true; Spring Boot does this by itself when it detects that it runs on Kubernetes. Point the pod's livenessProbe and readinessProbe at the two paths. Keep checks of external systems, such as a database, out of the liveness group, or an outage elsewhere makes Kubernetes restart every operator pod in a loop. The Actuator page covers health groups in detail.

Running the operator in the cluster (not run)

The operator needs permission to read and write its own resources and the resources it manages. A service account with a role like this one is the minimum for the Shop operator:

YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: shop-operator
rules:
  - apiGroups: ["shop.example.com"]
    resources: ["shops", "shops/status", "shops/finalizers"]
    verbs: ["get", "list", "watch", "patch", "update"]
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "list", "watch", "create", "patch", "update", "delete"]
  - apiGroups: ["coordination.k8s.io"]
    resources: ["leases"]           # for leader election
    verbs: ["get", "create", "update"]
  • Leader election: with two or more replicas for availability, only one may reconcile at a time, or both would fight over the same resources. JOSDK supports leader election through a Kubernetes Lease; the other replicas wait until the leader's lease expires.
  • Watched namespaces: an operator can watch all namespaces or a list of them. Fewer namespaces need fewer permissions, a Role instead of a ClusterRole, and less memory for the informer caches.
  • Memory: informers keep a copy of every watched resource in memory. Watching all pods or all secrets of a large cluster can need far more heap than the reconcile logic itself.
  • Container image: build it with ./mvnw spring-boot:build-image or a Dockerfile, as the Spring Docker page shows.

Testing an operator

  • Reconcile logic as plain Java: as the model shows, the comparison of desired and actual state needs no cluster. Keep it in methods that take and return plain objects, and test them with unit tests.
  • Desired state: test each dependent resource's desired method by calling it with a Shop and asserting on the returned Deployment.
  • API server tests: fabric8's mock server, or a real API server in a container started with Testcontainers, run the reconciler against Kubernetes APIs without a full cluster. JOSDK ships JUnit extensions that start the operator against such a server.
  • End-to-end tests: a local cluster such as kind or minikube, with the CRD and the operator image installed, checks RBAC, leader election and real Deployments.

Choosing whether to write an operator

When an operator is the right tool
SituationBetter choice
Deploying an application with fixed configurationPlain manifests, Kustomize or a Helm chart
Many similar deployments that differ in a few valuesA Helm chart, or an operator if the set changes at run time
Ongoing operational work: backups, upgrades, failoverAn operator
Kubernetes resources tied to resources outside the clusterAn operator with a finalizer
A team that already writes Spring and JavaJava Operator SDK with its Spring Boot starter
A small, fast operator image with few dependenciesJOSDK without Spring, or a Go operator

An operator earns its complexity when it encodes operational knowledge that would otherwise be a runbook. Keep the reconcile logic small, level-triggered and idempotent, and report honest status. For the probes and metrics of the operator itself, see the Actuator page.