How Kubernetes Operators Automate Stateful Apps
How Kubernetes Operators run databases and Kafka: CRDs, reconcile loops, failover, backups, capability levels, a CloudNativePG example and a checklist.
A Kubernetes Operator is a custom controller plus a custom resource that encodes how to run one application. For stateful systems such as PostgreSQL, MySQL or Kafka, the Operator watches the resource you declare and keeps reconciling the cluster toward it: creating replicas, electing a primary, failing over, taking backups, rotating certificates and running upgrades in the safe order.
Kubernetes handles stateless apps well with Deployments. Databases are harder: pods have identity, data must survive restarts, and operations such as failover or a major version upgrade need a specific sequence. StatefulSets give stable names and storage (see StatefulSet vs Deployment), but they do not know what a primary or a replication slot is. Operators fill that gap. This guide explains how they work, what they automate, how to judge one, and where they fall short. If you are preparing for interviews on the topic, the 75+ Kubernetes Operators interview questions and the six-week Operator interview prep plan are the companion posts.
Key takeaways
- An Operator is a CustomResourceDefinition (the API) plus a controller (the logic) that runs a reconcile loop.
- It automates "day 2" work: failover, backups, restores, scaling, upgrades and configuration changes, not just installation.
- Operators differ widely in maturity. The Operator Framework's five capability levels are a useful yardstick.
- An Operator does not remove the need to understand the database. When it fails, you still need someone who knows replication and recovery.
- Test backups by restoring them. An Operator that takes backups you never restore gives false comfort.
How an Operator works
The Kubernetes documentation describes the Operator pattern as using custom resources to manage applications and their components, following the control loop principle that Kubernetes itself uses. There are three parts.
1. The custom resource definition
A CRD adds a new type to the Kubernetes API, such as Cluster for PostgreSQL or Kafka for a Kafka cluster. After it is installed, you can kubectl get, apply and describe these objects like built-in ones, and RBAC rules apply to them.
2. The custom resource
You write a short manifest that states what you want: three instances, 50 GiB of storage each, PostgreSQL version 17, backups to an object store every night. You describe the outcome, not the steps.
3. The controller and its reconcile loop
The controller runs as a pod in the cluster. It watches its custom resources and the objects it owns (pods, PVCs, Services, Secrets). Whenever something changes, it runs a reconcile function:
- Read the desired state from the custom resource.
- Observe the actual state: which pods exist, which one is primary, how far replicas lag.
- Take the next action that moves actual towards desired, such as creating a replica or promoting a standby.
- Write progress to the resource's
statusfield and requeue.
Reconcile functions should be idempotent: running them twice in a row should not do anything harmful. That is what lets the controller recover after its own restart, a network blip or a missed event.
What Operators automate for stateful apps
| Task | Without an Operator | With a mature Operator |
|---|---|---|
| Provisioning a replicated cluster | StatefulSet, init scripts, manual replication setup | One custom resource |
| Primary failure | On-call engineer promotes a replica and repoints apps | Automatic promotion; Service endpoints follow the new primary |
| Backups | CronJobs and scripts you maintain | Declared schedule, continuous WAL or binlog archiving in many Operators |
| Point-in-time restore | Runbook with many manual steps | New resource that bootstraps from a backup to a timestamp |
| Minor version upgrade | Careful manual rolling restart | Change the image; replicas first, then switchover, then old primary |
| Scaling read replicas | Provision and configure each replica | Change the instance count |
| TLS certificates and users | Manual generation and rotation | Generated as Secrets and rotated |
| Monitoring | Hand-built exporters | Built-in metrics endpoint, often with ready dashboards |
Operator capability levels
The Operator Framework capability model describes five levels. Use it to judge how much an Operator really automates.
| Level | Name | What it means in practice |
|---|---|---|
| 1 | Basic Install | Deploys the application from a custom resource. |
| 2 | Seamless Upgrades | Upgrades the Operator and the application safely. |
| 3 | Full Lifecycle | Backups, restores, failure recovery and storage lifecycle. |
| 4 | Deep Insights | Metrics, alerts and log processing for the managed app. |
| 5 | Auto Pilot | Auto-scaling, auto-tuning and abnormality detection. |
For a production database, look for at least level 3. A level 1 Operator is close to a Helm chart; see the role of Helm for how the two differ.
Widely used Operators for stateful workloads
| System | Operator | Notes |
|---|---|---|
| PostgreSQL | CloudNativePG | CNCF project; manages instances directly without StatefulSets; Barman-based backups |
| PostgreSQL | Crunchy Data PGO | Uses pgBackRest for backups |
| PostgreSQL | Zalando postgres-operator | Built around Patroni for high availability |
| MySQL | MySQL Operator for Kubernetes (Oracle) | Manages InnoDB Cluster with MySQL Router |
| MySQL | Percona Operator for MySQL | Variants for Percona XtraDB Cluster and group replication |
| Apache Kafka | Strimzi | CNCF project; manages brokers, topics and users as resources |
| Elasticsearch | Elastic Cloud on Kubernetes (ECK) | Also manages Kibana and other Elastic Stack components |
| Redis | Several community and vendor Operators | Check licence and maintenance status carefully |
Project health changes over time, so check recent releases, open issues and the supported Kubernetes versions before you commit. OperatorHub.io lists many Operators with their declared capability level.
Example: a highly available PostgreSQL cluster with CloudNativePG
After installing the CloudNativePG Operator, this manifest asks for a three-instance PostgreSQL cluster:
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: orders-db
namespace: data
spec:
instances: 3
storage:
size: 50Gi
resources:
requests:
cpu: "1"
memory: 2Gi
kubectl apply -f orders-db.yaml
kubectl get cluster -n data orders-db
kubectl get pods -n data -l cnpg.io/cluster=orders-db
kubectl get svc -n data
The Operator creates one primary and two streaming replicas, plus Services: orders-db-rw always points at the primary, orders-db-ro at replicas, and orders-db-r at any instance. Applications connect to orders-db-rw. If the primary pod or its node fails, the Operator promotes a replica and updates the Service, so the connection string never changes.
Backups
Backups in CloudNativePG have been moving. From version 1.26 the built-in barmanObjectStore section is deprecated in favour of the Barman Cloud Plugin, which uses a separate ObjectStore resource and references it from the cluster. A sketch of the plugin approach looks like this:
spec:
plugins:
- name: barman-cloud.cloudnative-pg.io
isWALArchiver: true
parameters:
barmanObjectName: orders-backup-store
---
apiVersion: postgresql.cnpg.io/v1
kind: ScheduledBackup
metadata:
name: orders-db-nightly
namespace: data
spec:
schedule: "0 0 2 * * *"
cluster:
name: orders-db
method: plugin
pluginConfiguration:
name: barman-cloud.cloudnative-pg.io
Note that CloudNativePG's schedule format has six fields, with seconds first. Field names change between releases, so follow the Barman Cloud Plugin documentation for your installed version rather than copying this block as is.
What happens during an automatic failover
The details vary by Operator, but a mature PostgreSQL Operator follows a sequence like this when the primary fails:
- The controller notices the primary pod is not ready, or the node it runs on is gone, through Kubernetes watches and its own health checks.
- It waits a configured delay to avoid reacting to a brief blip.
- It picks the replica with the most recent data, usually by comparing replication positions.
- It makes sure the old primary cannot accept writes, for example by fencing or deleting the pod, to avoid two primaries.
- It promotes the chosen replica and updates the read-write Service to point at it.
- It reconfigures the remaining replicas to follow the new primary and, when the old node returns, rebuilds the old primary as a replica.
- It records events and updates the custom resource status so you can see what happened with
kubectl describe.
Applications see a short interruption while connections drop and reconnect. Make sure connection pools retry, and test failover in staging by deleting the primary pod and watching the timings.
How Operators fit CI/CD and GitOps
Because the database is a Kubernetes object, it can live in Git next to the application. Argo CD or Flux applies the custom resource; the Operator does the work. A change such as "add a replica" becomes a pull request that is reviewed and audited. See what GitOps is for the workflow.
Two cautions. First, protect database resources from accidental deletion: deleting the custom resource usually deletes the cluster. Use Argo CD sync options or finalizers and restrict who can delete. Second, schema migrations are application work, not Operator work. Run them through your pipeline with Flyway, Liquibase or your framework's tool.
Choosing an Operator: a checklist
- Failover: how does it detect failure, and how does it avoid two primaries (split brain)?
- Backups: full and incremental? Continuous log archiving for point-in-time recovery? Where are backups stored?
- Restore: is restore documented as a single declarative step? Have you tried it?
- Upgrades: minor versions, major versions and the Operator itself. What is the documented order?
- Observability: metrics endpoint, dashboards, events on the custom resource.
- Security: TLS by default, generated credentials as Secrets, the Operator's own RBAC scope (namespace or cluster-wide).
- Project health: release cadence, maintainers, licence, commercial support if you need it.
Limits and risks
- Abstraction leaks. When an Operator hits a case it does not handle, you are debugging both the database and the Operator's logic.
- Cluster-wide permissions. Many Operators need broad RBAC. Review what you grant, and prefer namespace-scoped installs where supported.
- Upgrade coupling. Operator versions support a range of Kubernetes and database versions. A cluster upgrade can force an Operator upgrade.
- Storage still matters. The Operator cannot fix slow or unreliable volumes. Choose a StorageClass with suitable performance and understand its zone behaviour.
- Managed services may be simpler. If you run on a cloud, a managed database such as Amazon RDS or Cloud SQL removes much of this work. Operators make most sense when you need portability, on-premises clusters or cost control.
Building your own Operator
Write one when you run an internal stateful system many times and its operations are well understood. Common frameworks:
| Framework | Language | Notes |
|---|---|---|
| Kubebuilder | Go | Kubernetes SIG project built on controller-runtime |
| Operator SDK | Go, Ansible, Helm | Uses Kubebuilder for Go; adds OLM integration |
| Kopf | Python | Lightweight; good for simpler controllers |
Start small: a CRD with a few fields, a reconcile function that creates the basic objects, status reporting, then add one day-2 operation at a time with tests against a real cluster such as kind.
Related reading
For database lifecycle details, see using Kubernetes Operators for database lifecycle automation. For how upgrades of stateful workloads fit into rollout planning, see 12 Kubernetes rollout strategies with examples. CRDs, controllers and StatefulSets are covered in our CKA training in Pune and CKAD training, in Kharadi or live online.
Frequently asked questions
What is a Kubernetes Operator?
It is a custom controller paired with a custom resource definition. You declare the application state you want in a custom resource, and the controller keeps the cluster matching it, including operational tasks like failover and backups.
How is an Operator different from a StatefulSet?
A StatefulSet gives pods stable names and persistent volumes. It does not understand the application. An Operator adds application knowledge, such as which pod is primary and how to promote a replica, and may or may not use StatefulSets underneath.
How is an Operator different from a Helm chart?
Helm renders and installs templates once per install or upgrade. An Operator runs continuously and reacts to changes and failures. Some teams install an Operator with Helm and then let the Operator manage the application.
Which Operator should I use for PostgreSQL?
CloudNativePG, Crunchy Data PGO and the Zalando postgres-operator are common choices. Compare their failover, backup tooling, upgrade process and support options against your needs, and test a restore before production use.
Do Operators make databases on Kubernetes production ready?
A mature Operator handles much of the operational work, but production readiness also depends on storage performance, tested restores, monitoring, resource limits and people who understand the database.
What are the Operator capability levels?
The Operator Framework defines five: Basic Install, Seamless Upgrades, Full Lifecycle, Deep Insights and Auto Pilot. Each level adds more automated operations.
Can I write a Kubernetes Operator in Python?
Yes. Kopf is a Python framework for writing Operators. Go with Kubebuilder or Operator SDK is more common for large Operators, and Operator SDK also supports Ansible and Helm based Operators.
References
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0