KubernetesIntermediate

StatefulSets vs Operators: Databases on Kubernetes

DeveloperHat Team
18 min read

TL;DR

StatefulSet or operator for Postgres and MySQL on Kubernetes? Compare backup, failover, upgrades, and day-2 burden — with the rule for when each earns its place.

A few years ago the argument was whether a database belonged on Kubernetes at all. For many teams that argument is over: the database runs in the cluster, next to the application, under the same GitOps pipeline and the same observability stack. The live question is how it runs — as a hand-rolled StatefulSet with a set of scripts you wrote, or as a declarative cluster managed by a dedicated operator.

Both paths start from the same Kubernetes primitive. A StatefulSet gives a database stable names, stable storage, and ordered startup, and for a single Postgres instance in development that is genuinely all you need. The difference shows up on day two, at 2 a.m., when the primary dies, when a backup has to restore to a point in time, or when Postgres 18 needs to become Postgres 19. This article compares the two paths on backup and restore, failover, upgrades, and the ongoing burden of owning them, and ends with a clear rule for when a StatefulSet is enough and when an operator earns its complexity. The guarantees quoted for StatefulSets come from the official StatefulSets documentation.

StatefulSet guarantees identity — not a database STATEFULSET GUARANTEES Stable identity postgres-0 keeps its name Stable storage one PVC per Pod Ordered startup OrderedReady, 0 then 1 then 2 IT DOES NOT DO Replication no leader election Failover no promotion Backups no point-in-time recovery Everything a database needs beyond Pods is your code — or an operator. The StatefulSet is the foundation; the operator is the platform built on it.

What a StatefulSet actually guarantees — and what it does not

A StatefulSet is a workload controller, not a database manager, and its contract is narrower than teams often assume. The official documentation lists four things it is valuable for: stable, unique network identifiers; stable, persistent storage; ordered, graceful deployment and scaling; and ordered, automated rolling updates. Each Pod gets a sticky identity — postgres-0, postgres-1 — that survives rescheduling, and the documentation guarantees that a given network identity always maps to the same storage identity. That identity is what makes a database on Kubernetes workable at all: when postgres-1 dies and is rescheduled to another node, it reattaches to its own volume, not a stranger's.

The storage half of the contract comes from volumeClaimTemplates. You declare a template once, and Kubernetes creates one PersistentVolumeClaim per Pod, named after the template, the StatefulSet, and the ordinal — data-postgres-0, data-postgres-1. By default those claims are retained until you delete them by hand, so scaling down or deleting the StatefulSet does not destroy the data. The ordering half comes from the pod management policy: the default OrderedReady creates Pods strictly in increasing order and waits for each one to be ready before starting the next, and scales down in the opposite order. The alternative, Parallel, launches everything at once and is the right choice only when the application itself handles the ordering.

Two requirements catch first-timers. A StatefulSet needs a headless Service (clusterIP: None) that you create yourself, because the Service is what gives each Pod its stable DNS entry. And the identity guarantee is about names and volumes, not about the database: the StatefulSet does not set up replication, does not elect a leader, does not take backups, and does not promote a replica when the primary fails. The documentation is equally honest about the sharp edges: a StatefulSet provides no guarantees about Pod termination when the StatefulSet itself is deleted — scale it to zero first if you want ordered shutdown — and a rolling update under the default OrderedReady policy can get into a broken state that needs manual intervention to repair. The Kubernetes storage guide covers the StorageClass and volume side of this setup in more depth.

That boundary is the whole article in miniature. Everything a StatefulSet promises is about the Pods. Everything a database needs beyond that — replication topology, failover, backup, upgrades — is either your code or someone else's operator.

The hand-rolled StatefulSet: what day 2 really looks like

The hand-rolled path starts simple and stays simple until the first incident. A StatefulSet with three Postgres Pods, a headless Service, and a volumeClaimTemplates entry is a working database in an afternoon:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
  namespace: db
spec:
  serviceName: postgres-headless
  replicas: 3
  podManagementPolicy: OrderedReady
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:18
        ports:
        - containerPort: 5432
        volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql/data
        resources:
          requests:
            cpu: "1"
            memory: 2Gi
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      storageClassName: fast-ssd
      resources:
        requests:
          storage: 100Gi

That manifest is a complete description of three Postgres processes with durable storage. What it does not describe is a database cluster. Postgres itself has no idea postgres-1 is supposed to be a replica of postgres-0; replication has to be configured inside the containers, usually by an entrypoint script that decides, on first boot, whether this Pod initializes a fresh cluster or joins as a standby, and by a replication user and primary_conninfo wired through Secrets. The moment you write that script, you own a small database product: it has to handle the first boot, the restart, the case where the primary is gone and a replica must be promoted, and the case where the old primary comes back and must not accept writes.

Failover is where the hand-rolled path earns its reputation for 2 a.m. pages. Without a controller watching the cluster, promotion is either manual — someone runs the promote command and repoints the read-write Service — or delegated to an external tool such as Patroni, which adds its own distributed consensus store and its own failure modes. Backups are a CronJob running pg_basebackup plus continuous WAL archiving to object storage, and the restore procedure is a runbook that nobody has run since it was written. Upgrades are a planned outage or a carefully sequenced replica rebuild: build the new major version, replicate, promote, and hope the application tolerates the cutover. The zero-downtime database migration guide covers the application-side patterns that make a cutover survivable.

None of this is impossible, and for a team that knows Postgres deeply it can be the right call. But count the surface honestly: the StatefulSet is the smallest part of the system. The entrypoint script, the failover procedure, the backup CronJob, the restore runbook, and the upgrade plan are the system, and they are all yours to write, test, and maintain. A hand-rolled StatefulSet is not a shortcut around database operations; it is a decision to do database operations by hand.

What an operator adds: a control loop that knows databases

An operator is a controller that watches a custom resource describing the desired database cluster and drives the real cluster toward it, continuously. The pattern itself is standard Kubernetes — the operators guide covers how custom controllers extend the API — but a database operator encodes knowledge that a generic controller cannot: how to bootstrap replication, when a replica is safe to promote, how to take a consistent backup, and how to roll a major-version upgrade without losing a transaction.

CloudNativePG is the clearest example for Postgres. You declare a cluster and the operator builds the rest:

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: pg-main
  namespace: db
spec:
  instances: 3
  postgresql:
    synchronous:
      method: any
      number: 1
  storage:
    size: 100Gi
    storageClass: fast-ssd

From that manifest the operator creates the StatefulSet, the PersistentVolumeClaims, the read-write and read-only Services, the Secrets, and the replication configuration — and then keeps watching. If the primary dies, the operator promotes the most up-to-date replica and repoints the read-write Service, so the application keeps connecting to the same name. Backups run through the Barman Cloud plugin to object storage, with continuous WAL archiving behind them, which is what makes point-in-time recovery possible. The operator is current and actively maintained: version 1.30.2 is the latest release, it became a CNCF Incubating project in November 2026 after entering the CNCF Sandbox in January 2025, its default image is PostgreSQL 18.7, and PostgreSQL 14 support ended on November 12, 2026, when the PostgreSQL community stopped fixing it. The CloudNativePG 1.30.2 release notes and the official quickstart are the sources for those version claims.

The other engines have their own mature operators, and the choice is per engine, not per cluster. Percona ships a family of them: the Operator for PostgreSQL is at 3.1.0, a 2026 major release built on a fork of Crunchy Data's PGO, with the 2.x line end-of-life on August 31, 2026; the Operator for MongoDB is at 1.23.1; the XtraDB Cluster operator for MySQL is at 1.20.0; and the Percona Server for MySQL operator is at 1.3.0. All four are Apache 2.0, and the Percona operators documentation lists the current releases. For MySQL at a scale where one primary stops being enough, Vitess is the sharding answer: version 24.0.0 shipped with operator 2.17.0 in April 2026, adding cluster- and keyspace-level scheduled backups, and it is a graduated CNCF project that has run some of the largest MySQL installations in production.

Five layers, one database cluster API layer — Cluster CRD · desired state in YAML Control loop — operator watches, reconciles, promotes Workload layer — StatefulSet · PVCs · headless Service Data layer — replication · WAL archiving · Barman backups Access layer — read-write + read-only Services, one DNS name The operator owns the API, control-loop and data layers; the StatefulSet is the workload layer. Delete the operator and the database keeps running — until the next failover.

The honest price of an operator is that it is software you now depend on. Its controller is a new single point of operational trust: its bugs become your outage, its upgrades are a second upgrade track alongside the database itself, and its custom resources are a small API you have to learn. A good operator repays that price many times over on the operations it automates. A bad or abandoned one is worse than no operator at all, because it hides the complexity instead of removing it. Check the release cadence and the support window before you commit — the version numbers above are the check to run, not a permanent recommendation.

Architecture decision: hand-rolled StatefulSet or a dedicated operator

Decision

Use a dedicated, actively maintained database operator for any production database on Kubernetes. Reserve the hand-rolled StatefulSet for single-instance, non-HA workloads that can be rebuilt from scratch.

Context

Our databases run on Kubernetes, and the team operating them is small. The workloads that hurt most from a database incident are the ones with real users and real data: the primary application database, anything with a recovery point objective measured in minutes, and anything whose restore has never been rehearsed. Before this decision, every database was a hand-written StatefulSet plus scripts, which meant every failover, backup, and upgrade was a manual procedure owned by whoever happened to be on call.

Options considered

First, keep the hand-rolled StatefulSet for everything, and invest in better scripts and runbooks. Second, adopt a dedicated operator per engine — CloudNativePG for Postgres, the Percona operators for MySQL and MongoDB, Vitess where MySQL needs sharding — and let the controller own replication, failover, backup, and upgrades. Third, move production databases out of the cluster entirely to a managed service and keep only development databases on Kubernetes. Fourth, adopt an operator only for Postgres and keep the other engines hand-rolled.

Why this one

The second option fits the actual guarantees. A StatefulSet guarantees Pod identity and storage identity; it does not guarantee a working database cluster, and the scripts that close that gap are the least-tested code in the system. An operator closes the gap with a control loop that runs the same failover and restore logic every time, including at 2 a.m. when nobody is awake to run the runbook. The third option is genuinely better for some teams — a managed database is the right answer when the team has nobody to own the operator — but it is a different decision about where the database lives, not about how to run one in the cluster. The fourth option splits the operational model for no benefit: if the team can own one operator, it can own the pattern.

What it costs you

The operator is a new dependency with its own upgrade track, its own RBAC footprint, and its own failure modes, and the team has to learn its custom resources and its status reporting. You also accept a smaller blast radius of choice: switching operators later is a migration, not a configuration change. And you take on the obligation to keep the operator itself current — an operator two years out of date is a liability, not a convenience.

When to reverse it

If the operator's project stalls — no releases for a year, a shrinking maintainer base, a support window that lapses — start planning the exit, because an unmaintained controller is worse than scripts you control. If the workload turns out to be a single-instance database with no availability requirement and a restore path that is simply re-seeding from source, the hand-rolled StatefulSet is the right answer after all, and the operator's complexity is pure overhead. And if the team decides it cannot staff the operator at all, the honest reversal is the managed service, not the hand-rolled scripts.

Backup and restore: the test that separates the two

Backups are easy to claim and hard to prove, and the difference between the two paths is not whether backups exist but whether restores have been rehearsed. A hand-rolled setup usually has backups: a CronJob runs pg_basebackup on a schedule and WAL files are archived to object storage. The restore is where it falls apart. Restoring to a point in time means provisioning a fresh Postgres, replaying WAL files up to the target timestamp, verifying the result, and repointing the application — a sequence that lives in a runbook, runs rarely, and breaks silently when the backup job's assumptions drift. Most teams discover their restore is broken at the exact moment they need it.

An operator turns the restore into a declarative operation of the same kind as the backup. With CloudNativePG, scheduled backups and continuous WAL archiving go to the same object store through the Barman Cloud plugin, and a point-in-time recovery is a new Cluster resource bootstrapped from a recovery target — the same fields, the same validation, no runbook. The operator also makes the backup schedule visible as cluster state rather than as a CronJob buried in another namespace, which means a missed backup shows up in the same status output as a failed replica.

The discipline is the same on both paths and it is not optional: schedule the restore drill, time it, and record how long it took. A backup you have never restored is a hope, not a recovery plan. The operator makes the drill cheaper to run and easier to repeat, which is the practical reason teams that adopt one end up with tested restores and teams that hand-roll often do not. If you can only change one thing about your current setup, make it a quarterly restore rehearsal — with either architecture, that single habit is worth more than any feature comparison in this article.

Failover and upgrades, head to head

Failover and upgrades are the two operations where the operator's control loop shows its value most directly, and they are also the two where a hand-rolled setup is most likely to be tested under pressure for the first time. The comparison below assumes a three-replica Postgres cluster on both sides.

Hand-rolled StatefulSetDedicated operator
Failover triggerManual, or an external tool such as PatroniController detects primary loss and promotes automatically
Promotion choiceWhoever runs the procedure picks the replicaOperator promotes the most up-to-date replica
Client redirectSomeone repoints the read-write ServiceOperator repoints the read-write Service itself
Backup scheduleCronJob you wrote, in a namespace you choseDeclarative schedule, visible in cluster status
Point-in-time recoveryManual WAL replay from a runbookDeclarative recovery target on a new cluster
Minor upgradeRolling restart, scripted or manualRolling update driven by the controller
Major upgradeReplica rebuild and manual promotionManaged in place, with switchover instead of restart where supported
Day-2 ownerYour scripts, your runbooks, your on-callThe operator's control loop, plus your operator upgrades
Worst failure modeA runbook step skipped under pressureAn operator bug, or an operator left years out of date

StatefulSet or operator for this database? Start from who owns day two, not from the manifest. Production data with HA needs? backups, failover, upgrades No — single instance StatefulSet + volume Yes — team can own it Operator per engine Yes — nobody can own it Managed service Operator project stalled? plan the exit Pick the shape of ownership your team can actually staff.

The table understates the failover difference. A manual failover has a human in the loop at the worst possible time: the person promoting the replica has to be sure it is the most up-to-date one, sure the old primary is fenced so it cannot accept writes again, and sure the application is pointed at the new primary. Each of those is a judgement call under pressure, and each has a known failure mode — split brain from an unfenced primary is the classic one. The operator makes the same judgements from the same data every time, and it makes them in seconds rather than after someone's phone rings. That is not a claim about a specific failover time in seconds; it is a claim about removing the human from the critical path, which is the part you can verify by drilling it.

Drill it, on either path. The cheapest useful test is to delete the primary Pod and watch what happens:

kubectl delete pod pg-main-1 --namespace db
kubectl cnpg status pg-main --namespace db

On the operator path the status output should show a new primary elected and the read-write Service repointed, with no manual step. On the hand-rolled path the same command shows you exactly how much of the procedure is automated and how much is a page to a human. Run the test in staging first, time it, and write down what you saw — the result is the real comparison, and it is specific to your cluster in a way no article can be.

When NOT to use an operator — and when NOT to run the database here

An operator is not the answer for every database in the cluster, and the cases where it is the wrong tool are worth naming plainly. A single-instance database in development or CI — the one that exists so tests have something to connect to — does not need failover, point-in-time recovery, or a control loop; a bare StatefulSet with a volume is less to own and faster to throw away. Ephemeral databases for preview environments are the same story: if the data is disposable, the operator's guarantees are solving a problem you do not have. And if the engine you run has no mature operator — an unusual or new database with a controller that has not seen a production incident — the hand-rolled StatefulSet plus honest runbooks is safer than trusting an unproven control loop with your data.

The bigger question is whether the database should be in the cluster at all. A managed database is the right answer more often than Kubernetes enthusiasts admit: the cloud provider takes backups, failover, patching, and major upgrades, and your team gets the time back. If nobody on the team is willing to own the operator — to upgrade it, to read its status output, to drill the failover — then the managed service is not the expensive option; it is the only option that does not quietly become an unmaintained dependency. The same applies to databases with strict performance or compliance needs: local NVMe throughput, data-residency rules, or audit requirements that a shared cluster cannot satisfy are all reasons to keep the database outside Kubernetes, or on dedicated nodes at minimum.

The rule that covers both decisions is ownership. Whichever path you pick, someone has to own the database's day two: the backups, the restores, the upgrades, and the 2 a.m. page. An operator concentrates that ownership into one component you can learn and monitor. A hand-rolled StatefulSet spreads it across scripts and runbooks that only their author understands. A managed service moves it to the provider. Pick the shape of ownership your team can actually staff, and be honest when the answer is that you cannot staff any of them yet.

Recommendation

For a production database on Kubernetes, adopt the dedicated operator for your engine and keep the hand-rolled StatefulSet for the workloads that do not need high availability. The rollout order that has worked for teams making this move is: first, pick the operator per engine — CloudNativePG 1.30.x for Postgres, the current Percona operator for MySQL or MongoDB, Vitess 24 where MySQL needs sharding — and install it in a non-production namespace, where a mistake costs nothing. Second, stand up a three-instance cluster from the declarative manifest and drill the two operations that matter: delete the primary Pod and confirm the failover, then restore a backup to a point in time and confirm the data. Third, promote the operator to production only after both drills have been run and timed, and write the timings down — they are your recovery objectives, measured rather than assumed.

Keep the bare StatefulSet for development, CI, and preview environments, where a single instance with a volume is the whole requirement and the operator would be pure overhead. Revisit the decision when the operator's project health changes, when a new engine enters the stack, or when the managed-service pricing changes enough to reopen the question. The StatefulSet is not going away — every operator in this article builds on one — but it is a building block, not a database platform. Use it as the foundation, and let the operator be the platform.

Why This Matters

Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

Trade-offs to Consider

Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

When NOT to Use This

Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

Decision Framework

Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

Share this articleShare on XShare on LinkedIn

Keep the decision frameworks coming

One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.